반응형
접근자 프로퍼티는 자체적으로 값을 갖지 않고 다른 데이터 프로퍼티의 값을 읽거나 저장할 때 사용하는 접근자 함수로 구성된 프로퍼티이다. 접근자 프로퍼티는 다음과 같은 프로퍼티 어트리뷰트를 갖는다
get | 접근자 프로퍼티를 통해 데이터 프로퍼티 값을 읽을때 호출되는 접근자 함수이다.접근자 프로퍼티 키로 프로퍼티 값에 접근하면 프로퍼티 어트리뷰터 [[getter]]의 값, getter함수가 호출되는 것이다 |
set | 접근자 프로퍼티를 통해 데이터 프로퍼티의 값을 저장할 때 호출되는 접근자 함수다. 접근자 프로퍼티 키로 값을 저장하면 프로퍼티 어트리뷰트의 [[setter]]의 값, setter함수가 호출되는 것이다. |
enumerable | 데이터 프로퍼티의 enumerable과 동일한 성격 |
configurable | 데이터 프로퍼티의 configurable과 동일한 성격 |
const Person = {
firstname : "Park", // 데이터 프로퍼티
lastname : "Jaehan", // 데이터 프로퍼티
//접근자 프로퍼티
get fullName(){
return `${this.firstname} ${this.lastname}`;
},
//접근자 프로퍼티
set fullName(name){
[this.firstname, this.lastname] = name.split(' ');
}
};
// 접근자 프로퍼티로 값을 저장하려고 하는것이기 떄문에, setter함수가 호출되게 된다
Person.fullName = "Yoon Junho";
//접근자 프로퍼티로 값을 읽어들이려고 하는것이기 때문에 getter함수가 호출되게 된다.
console.log(Person.fullName);
let descirptor = Object.getOwnPropertyDescriptors(Person);
/**
* {
firstname: {
value: 'Yoon',
writable: true,
enumerable: true,
configurable: true
},
lastname: {
value: 'Junho',
writable: true,
enumerable: true,
configurable: true
},
fullName: {
get: [Function: get fullName],
set: [Function: set fullName],
enumerable: true,
configurable: true
}
}
*/
descirptor = Object.getOwnPropertyDescriptor(Person, "fullName");
console.log(descirptor);
데이터 프로퍼티와 접근자 프로퍼티의 구분은 getOwnPropertyDescriptor()함수를 통해 볼 수 있다.
// 일반적인 __proto__는 접근자 프로퍼티
console.log(Object.getOwnPropertyDescriptor(Object.prototype, '__proto__'));
//일반적인 함수는 데이터 프로퍼티이다.
console.log(Object.getOwnPropertyDescriptor(function(){},'prototype'))
/**
* {
get: [Function: get __proto__],
set: [Function: set __proto__],
enumerable: false,
configurable: true
}
{ value: {}, writable: true, enumerable: false, configurable: false }
*
*/
반응형