자바스크립트 엔진은 프로퍼티를 생성할 때 프로퍼티의 상태를 나타내는 프로퍼티 어트리뷰트를 기본값으로 자동 정의한다.
프로퍼티 어트리뷰트는 내부 슬롯이기때문에 직접 접근할 수는 없지만 메서드를 통해서 간접적으로 확인할 수 있다.
const person = {
name: 'Lee',
age: 13,
};
console.log('name' in person);
// 자바스크립트 엔진은 프로퍼티를 생성할 때 프로퍼티의 상태를 나타내는 프로퍼티 어트리뷰트를 기본값으로 자동 정의한다
// 프로퍼티의 상태 - value, writable, enumerable, configurable
console.log(Object.getOwnPropertyDescriptor(person, 'name'));
console.log(Object.getOwnPropertyDescriptors(person));
해당 메서드를 통해 프로퍼티 어트리뷰트를 확인할 수 있는 프로퍼티 디스크립터
객체를 반환받을 수 있다.
프로퍼티는 데이터 프로퍼티
와 접근자 프로퍼티
로 구분할 수 있다.
const person2 = {
// 데이터 프로퍼티
firstName: '찬욱',
lastName: '박',
// fullName은 접근자 함수로 구성된 접근자 프로퍼티
// getter와 setter 함수는 접근자 프로퍼티이다. 이들은 데이터 프로퍼티의 값을 읽거나 저장하는 거에만 관여한다.
get fullName() {
return `${this.firstName} ${this.lastName}`;
},
set fullName(name) {
[this.firstName, this.lastName] = name.split(' ');
},
};
person2.fullName = '미란 박';
console.log(person2.fullName);
데이터 프로퍼티와 접근자 프로퍼티가 갖는 프로퍼티 어트리뷰트는 다르다. 헷갈렸던 부분은 접근자 프로퍼티의 어트리뷰트에 get과 set이 존재한다는 점이였다.
const person3 = {};
Object.defineProperties(person, {
firstName: {
value: '찬욱',
writable: true,
enumerable: true,
configurable: true,
},
lastName: {
value: '박',
writable: true,
enumerable: true,
configurable: true,
},
fullName: {
get() {
return `${this.firstName} ${this.lastName}`;
},
set(name) {
[this.firstName, this.lastName] = name.split(' ');
},
enumerable: true,
configurable: true,
},
});
결국에 프로퍼티를 정의하는 방법은 프로퍼티 디스크립터 객체의 프로퍼티에 접근하는 것이다.
이전에 fullName에 get과 set을 왜 정의할 수 있는지 이해가 되지 않았는데 fullName은 접근자 프로퍼티이고 때문에 디스크립터 객체의 프로퍼티로 get과 set을 가질 수 있기 때문에 정의할 수 있는 것이다.
중요한 점은 해당 메서드를 외우는 것이 아니라 객체의 프로퍼티 어트리뷰트에 직접적으로 접근하진 못해도 어트리뷰트의 상태를 보여주는 디스크립터 객체를 통해 변경가능하다는 것이다.
정보에 감사드립니다.