//객체 리터럴을 사용한 객체 생성
let obj = {
key1: 'value1',
printKey1: function(){
console.log(`${this.key1}`);
}
};
obj.printKey1(); //value1
//프로퍼티 키가 식별자 네이밍 규칙을 따르는 경우
//따옴표 생략 가능
let obj1 = {
firKey: 'value',
'sec-key': 'value' //식별자 네이밍 규칙을 따르지 않는 경우
};
//프로퍼티 키의 동적 생성
//존재하지 않는 프로퍼티 키를 선언하고 값을 할당할 수 있다.
let obj2 = {};
var key = 'Key'
obj2.secKey = 'value2'
obj2[`fir${key}`] = 'value1';
console.log(obj2.firKey); //value1
console.log(obj2.secKey); //value2
//프로퍼티 접근
//dot noatation
console.log(obj2.firKey); //value1
//bracket notation
console.log(obj2['secKey']); //value2
//선언하지 않은 프로퍼티에 접근
console.log(obj2.thrKey); //undefined
//선언된 프로퍼티지만 잘못 접근한 경우
console.log(obj2[secKey]); //ReferenceError: secKey is not defined
//프로퍼티 삭제
delete obj2.secKey;
console.log(obj2); //{ firKey: 'value1' }
//축약 표현
//변수로 프로퍼티 생성
let key1 = 'value1', key2 = 'value2';
let obj3 = {key1, key2};
console.log(obj3); //{ key1: 'value1', key2: 'value2' }
// 메소드 생성
// 추가 학습 필요
let obj4 = {
printHello(){
console.log('hello');
}
};
console.log(obj4.printHello()); //hello
// undefined
출처
이웅모, 모던 자바스크립트 Deep Dive(2021)