2. 목차
객체란?
객체 리터럴
생성자 함수
New를 강제하는 패턴
배열 리터럴
JSON
정규 표현식 리터럴
원시 데이터 타입 래퍼
에러 객체
정리
3. 리터럴 & 객체
리터럴이란?
문자열 자체가 값을 나타내는 것
x = “90”
객체란?
이름 붙은 값들의 모음이다.
image 이름의 객체에
width, height 프로퍼티 2개가 있을 시
image.width
image.height
4. 객체 리터럴 문법
1.객체를 중괄호( { } )로 감싼다.
2.객체 내의 프로퍼티와 메서드를 쉼표로 분리한다. 마
지막에는 붙이지 않는다.
3.프로퍼티명과 프로퍼티 값은 콜론으로 분리한다.
4.객체를 변수에 할당할 때는 닫는 중괄호 뒤에 세미콜
론을 빼먹지 않도록 하라.
5. 빈 객체
빈 객체란?
Object.prototype에서 상속받은 프로퍼티와 메서드를 가
진다.
„비어있다‟는 말은 어떤 객체가 상복받은 것 외에는 자신
의 프로퍼티를 갖고 있지 않다는 뜻으로 이해 가능하다
6. 객체 리터럴 (1)
객체는 이름-값 쌍의 해시 테이블과 비슷하다
원시 테이터 타입과 객체(복합 데이터) 모두 값이 될
수 있다.
함수도 값이 될 수 있으며 이런 함수는 메서드라고
부른다.
* Primative data type, Composite data type
7. 객체 리터럴 (2)
빈 객체 생성
var dog = { }
프로퍼티 추가
dog.name = “Benji”;
메서드 추가
dog.getName = fucntion () {
return dog.name;
};
8. 객체 생성자
자바스크립트에는 클래스가 없기 때문에 유연하다.
객체 생성 - 리터럴 사용
var car = { goes: “far”};
// 내장 생성자 사용 (안티패턴)
var car = new Object();
car.goes = “far”;
리터럴 표기법을 사용하면 유효범위 판별 작업도 발
생하지 않는다.
9. 객체 생성자 – 함정 (1)
생성자가 인자를 받을 수 있어서 인자로 전달되는 값에 따라
다른 내장 생성자 객체 생성을 위임 할 수 있어서 다른 객체
가 반환 되기도 한다.
var o = new Object();
console.log(o.constructor === Object); //true
var o = new Object(1);
console.log(o.constructor === Number); //true
console.log(o.toFixed(2)); //”1.00”
10. 객체 생성자 – 함정 (2)
var o = new Object(“I am a string”);
console.log(o.consturctor === String); //true
console.log(typeof o.substring); //”function”
var o = new Object(true);
console.log(o.constructor === Boolean); //true
11. 사용자 정의 생성자 함수(1)
직접 생성자 함수를 만들어 객체 생성
var adam = new Person(“Adam”);
adam.say(); //”I am Adam”
Person은 그저 보통의 함수일 뿐이다 (클래스가 없
으므로)
var Person = fuction(name) {
this.name = name;
this.say = function() {
return “I am “ + this.name;
};
};
12. 사용자 정의 생성자 함수(2)
var Person = function(name) {
// var this = { };
//위 라인이 빠진 것이다
this.name = name;
this.say = function() {
return “I am “ + this.name;
};
//this를 반환한다.
// return this;
};
13. 사용자 정의 생성자 함수(3)
new 로 생성자 함수를 호출 시
빈 객채 생성
This라는 변수 참조 가능
해당 함수의 프로토타입을 상속 받음
This로 참조 되는 객체 프로퍼티와 메서드가 추가된다
반환되는게 없을 경우 this로 참조된 객체를 반환한다
14. 사용자 정의 생성자 함수(4)
바뀌지 않고 재사용이 필요할 시
프로토타입을 쓰는것이 좋다
person.prototype.say = function() {
return “I am “ + this.name;
};
var this = Object.create(Person.prototype);
15. 사용자 정의 생성자 함수(5)
빈 객체
var this = {};
var this = Object.create(Person.prototype);
Object.create는 다음장에…
16. 생성자 반환 값
생성자 함수를 new와 함께 호출하면 항상 객체가 반
환된다.
함수 내에 return문을 쓰지 않았더라도 생성자는 암
묵적으로 this를 반환한다.
또한 바환 값이 될 객체를 따로 정할 수도 있다.
var Objectmaker = function() {
this.name = “This is it”;
var that = {};
that.name = “And that‟s that”;
return that;
};
17. NEW를 강제하는 패턴(1)
New없이 생성자를 호출하면 this가 전역 객체를 가
리키게 된다.
function Waffle() {
this.taste = “yummy”;
}
var good morning = new Waffle();
console.log(typeof good_morning); //”object”
console.log(window.tastes); //”yummy”
New를 빼먹을시 good_morning은 undefined로 나온
다
18. NEW를 강제하는 패턴(2)
function Waffle() {
var that= {};
that.taste = “yummy”;
return that;
}
function Waffle() {
return {
tastes: “yummy”
};
}
그러나 이 방법은 프로토타입에 추가한 맴버를 객체에서 사용 불가
var first = new Waffle(), second = Waffle();
console.log(first.tastes); //”yummy”
console.log(second.tastes); //”yummy”
19. 스스로를 호출하는 생성자
function Waffle() {
if (!(this instanceof Waffle)) {
return new Waffle();
}
this.taste = “yummy”;
}
Waffle.prototype.wantAnother = true;
var first = new Waffle(),
second = Waffle();
console.log(first.tastes); //”yummy”
console.log(second.tastes); //”yummy”
console.log(first.wantAnother); // true
console.log(second.wantAnother); // true
20. 배열 리터럴(1)
Array() 생성자
var a = new Array(“itsy”, “bitsy”, “spider”);
var a = [“itsy”, “bitsy”, “spider”];
배열도 객체 “object” 출력한다
console.log(typeof a);
console.log(a.constructor === Array); // true
21. 배열 리터럴(2)
New Array()의 단점
var a = [3];
console.log(a.length); //1
console.log(a[0]); //3
var a = new Array(3);
console.log(a.length); //3
console.log(typeof a[0]); // “undefined”
new Array 에서는 부동소수점을 넣을시 에러가 난다
var white = new Array(256).join(„ „);
는255개의 공백문자 문자열을 반환한다.
22. 배열 판별 방법(1)
Array.isArray([]); //true
Array.isArray({
length: 1,
“0”: 1,
slice: function() {}
}); // false
또는
Object.prototype.toString() 호출시 가능
“[object Array]” 는 배열이고
“[object object]” 는 객체이다
24. JSON
JavaScript Object Notation의 준말
데이터 전송 형식의 일종
배열과 객체 리터럴 표기법의 조합
{“name”: “value”, “some”: [1,2,3]}
- 프로퍼티명에도 따옴표가 필요하다
함수나 졍규식 리터럴을 사용할 수 없다.
25. JSON 사용(1)
var jstr = „{“mykey”: “my value”}‟; // 공통
var data = eval(„ („ + jstr + ;) ;); //안티(보안)
var data = JSON.parse(jstr); //위라인 대신
console.log(data.mykey); //”my value”
// javascript YUI 사용
YUI().use(„json-parse‟, function(Y) {
var data = Y.JSON.parse(jstr);
console.log(data.mykey); //”my value”
});
// jQuery 사용
var data = jQuery.parseJSON(jstr);
console.log(data.mykey); //”my value
26. JSON 사용(2)
var dog = {
name: “Fido”,
dob: new Data(),
legs: [1, 2, 3, 4]
};
var jsonstr = JSON.stringify(dog);
위 메서드는 객체 또는 배열을 인자로 받아 JSON 문
자열로 직렬화한다
{“name”:”Fido”, “dob”:”2010-04-
11T22:36:22.436Z”, “legs”:[1,2,3,4])}
27. 졍규 표현식 리터럴
New RegExp() 생성자 사용
var re = //gm;
정규식 리터럴 사용
Var re = new RegExp(“”, “gm”);
28. 정규식 문법
g 전역 매칭
m 여러 줄 매칭
i 대소문자 구분없이 매칭
var no_letters = “abc123XYZ”.replace(/[a-
z]/gi, “”);
console.log(no_letters); //123
매칭을 미리 알 수 없거나 런타임에 문자열이 만들어
질시에는 RegExp()를 사용
29. 원시 데이터 타입 래퍼(1)
var n = 100;
console.log(typeof n); //”number”
var nobj = new Number(100);
console.log(typeof nobj); //”object”
var s = “hello”;
console.log(s.toUpperCase()); //”HOLLO”
“monkey”.slice(4, 6); //”key”
(22 /7).toPrecision(3); //”3.14”
30. 원시 데이터 타입 래퍼(2)
var s = new String(“my string”);
var n = new Number(101);
var b = new Boolean(true);
var s = “my string”;
var n = 101;
var b = true;
var greet = “Hello there”;
greet split(„ „)[0]; //”Hello”
greet smile = true;
typeof greet.smile; //”undefined”
31. 원시 데이터 타입 래퍼(3)
typeof Number(1); // “number”
typeof Number(“1”); // “number”
typeof Number(new Number()); // “number”
typeof String(1); //”string”
typeof Boolean(1); //”boolean”
32. 에러 객체
name, message이 기본 프로퍼티이다
그 외에도 임의의 프로퍼티를 가질 수 있다
try {
throw {
name: “MyErrorType”,
message: “oops”,
extra: “This was rather embrrassing”,
remedy: genericErrorHandler
};
} catch (e) {
alert(e.message); // “oops”
e.remedy(); // genericErrorHandler() 호출
}