프로퍼티 어트리뷰트는 자바스크립트의 객체동작을 제어하고 정의하는데 중요한 역할을 한다.
자바스크립트 객체의 속성(attribute)에 대한 설명을 나타내는데 사용되는 메타데이터로
각각의 객체 속성은 value(값), Writable(쓰기 가능 여부), Enumerable(열거 가능 여부), Configurable(설정가능여부) 라는 속성(attribute)을 갖는다.
let obj = {};
Object.defineProperty(obj,'myProperty',{
value: 42,
writable: false,
enumerable: true,
configurable: true
});
console.log(obj) // { myProperty: 42 }
let obj2 ={
myProperty:{
value:42,
writable: false,
enumerable: true,
configurable: true
}
}
console.log(obj2); // { myProperty: { value: 42, writable: false, enumerable: true, configurable: true } }
console.log(obj2.myProperty); // { value: 42, writable: false, enumerable: true, configurable: true }
Object.defineProperty() 메서드로 속성을 정의할 때는 해당 속성이 직접 객체에 추가되지 않는다. 대신, 명시적으로 정의한 속성을 가리키는 프로퍼티를 생성하게 된다.
따라서 console.log(obj)에서는 myProperty가 직접 나타나지 않고, 해당 객체에 대한 뷰(view)를 제공하는 프로퍼티를 출력한다. Object.defineProperty() 메서드를 사용하면 직접적으로 속성이 객체에 추가되지 않기 때문에 외부에서는 해당 속성을 직접 볼 수 없다.
let obj = {
_myValue: 0,
get myAccessorProperty() {
return this._myValue;
},
set myAccessorProperty(value) {
this._myValue = value;
}
};