Property Attribute

wonyoung·2024년 1월 31일

Javascript

목록 보기
10/36

1 ) 데이터 프로퍼티 - 키와 값으로 형성된 실질적 값을 갖고있는 프로퍼티
2 ) 액세서 프로퍼티 - 자체적으로 값을 갖고있지 않지만 다른 값을 가지거나 설정할 때 호출되는 함수로 구성된 프로퍼티 ex)getter setter

const wonYoung = {
    name: '이원영',
    year: 1997,
};

// console.log(Object.getOwnPropertyDescriptor(wonYoung, 'name'));

/**
 * { value: '이원영', writable: true, enumerable: true, configurable: true }
 * 
 * 1) value - 실제 프로퍼티의 값
 * 2) writable - 값을 수정 할 수 있는지 여부. false로 설정하면 프로퍼티 값을 수정할 수 없다.
 * 3) enumerable - 열거가 가능한 지 여부이다. for...in 룹 등을 사용할 수 있으면 true를 반환한다.
 * 4) configurable - 프로퍼티 어트리뷰트의 재정의가 가능한지 여부를 판단한다. false일 경우 프로퍼티 삭제나 어트리뷰트 변경이 금지된다. 단, writable이 true인 경우 값 변경과 writable을 변경하는건 가능하다.
 */

const wonYoung2 = {
    name: '이원영',
    year: 1997,

    get age() {
        return new Date().getFullYear() - this.year;
    },

    set age(age) {
        this.year = new Date().getFullYear() - age;
    }

}
// console.log(wonYoung2);

wonYoung2.age = 100;
// console.log(wonYoung2);
// wonYoung2.height = 172;

// console.log(Object.getOwnPropertyDescriptor(wonYoung2, 'height'))

Object.defineProperty(wonYoung2, 'height', {
    value: 172,
    writable: true,
    enumerable: true,
    configurable: true

});

Object.defineProperty(wonYoung2, 'height', {
    configurable: false
});
console.log(Object.getOwnPropertyDescriptor(wonYoung2, 'height'));


Object.defineProperty(wonYoung2, 'name', {
    enumerable: false,
});

for (let key in wonYoung2) {
    console.log(key)
}

writable true 값 변경 가능 / false 값변경 불가
enumerable true 열거 가능 / false 열거 불가 ( 값이 사라지진 않는다.)
configurable true 재정의 가능/ false 재정의 불가

profile
😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀

0개의 댓글