모던자바스크립트 Deep Dive에서 발췌한 객체 리터럴에 관한 내용을 적어보자
프로퍼티와 메서드로 구성된 집합체
JS는 객체 기반의 프로그래밍 언어이다. JS를 구성하는 "거의 모든 것"이 객체
원시값을 제외한 나머지 값(함수, 배열, 정규표현식 등)은 모두 객체
원시값과 객체타입의 비교
프로퍼티와 메서드
리터럴 : 사람이 이해할 수 있는 문자 또는 약속된 기호를 사용하여 값을 생성하는 표기법
var person = {
// 프로퍼티 키는 name, 프로퍼티 값은 'Lee'
name: 'Lee',
// 프로퍼티 키는 age, 프로퍼티 값은 20
age: 20
};
var obj = {};
var key = 'hello';
// ES5: 프로퍼티 키 동적 생성
obj[key] = 'world';
// ES6 : 계산된 프로퍼티 이름
// var obj = { [key]: 'world' };
console.log(obj); //{hello: "world"}
var foo = {
0 : 1,
1 : 2,
2 : 3
};
console.log(foo); // {0:1, 1:2, 2:3}
var foo = {
name : 'Lee',
name : 'Kim'
};
console.log(foo); // {name:"Kim"}
var circle = {
radius: 5, // <- 프로퍼티
// 원의 지름
getDiameter: function () { // <- aptjem
return 2 * this.radius; // this는 circle을 가리킨다.
}
};
console.log(circle.getDiameter()); // 10
var person = {
name: 'Lee'
};
// person 객체에 name 프로퍼티가 존재하므로 name 프로퍼티의 값이 갱신된다.
person.name = 'Kim';
console.log(person); //{name : 'Kim'}
var person = {
name: 'Lee'
};
person.age=20;
console.log(person); //{name : 'Kim', age:20}
var person = {
name: 'Lee'
};
person.age=20;
console.log(person); //{name : 'Lee', age:20}
delete person.age;
console.log(person); //{name : 'Lee'}
delete person.address;
console.log(person); //{name : 'Lee'}