Property Attribute

728x90

Data Property

- 키와 값으로 형성된 실질적 값을 가지고 있는 프로퍼티

Accesor Property

- 자체적으로 값을 가지고 있지 않지만 다른 값을 가져오거나 설정할 때 호출되는 함수로 구성된 프로퍼티, getter or setter

Data Propety 확인 - getOwnPropertyDescriptor

- value : 실제 프로퍼티 값
- writable : 값을 수정 할 수 있는지 여부, false로 설정하면 프로퍼티 값을 수정할 수 없다.
- enumerable - 열거가 가능한지 여부, for... in 루프 등을 사용할 수 있으면 true를 반환한다.
- configurable - 프로퍼티 Attribute의 재정의가 가능한지 판단한다. false일 경우 프로퍼티 삭제나 Attribute 변경이 금지된다. 단 writable이 true인 경우 값 변경과 writable을 변경하는 것은 가능하다.

const company = {
    name: 'planb',
    year: 1987,
};

console.log(Object.getOwnPropertyDescriptor(company, 'name'));
console.log(Object.getOwnPropertyDescriptors(company));

output

setter & getter

const company = {
    name: 'planb',
    year: 1987,

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

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

console.log(company);
console.log(company.age);

company.age = 32;
console.log(company.age);
console.log(company.year);

output

Accesor Propety 확인 - getOwnPropertyDescriptor

const company = {
    name: 'planb',
    year: 1987,

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

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

console.log(Object.getOwnPropertyDescriptor(company, 'age'));

output

Property 생성 방법

- defineProperty() 사용하면 속성값을 정의할 수 있음.

const company = {
    name: 'planb',
    year: 1987,

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

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

Object.defineProperty(company, 'industry', {
    value: 's/w',
    writable: false,
    enumerable: true,
    configurable: true,
})
console.log(company);
console.log(Object.getOwnPropertyDescriptor(company, 'industry'));

output

728x90

'JavaScript' 카테고리의 다른 글

함수를 이용한 객체 생성  (2) 2025.03.01
Immutable Objects  (0) 2025.03.01
객체 OOP 생성 방법  (0) 2025.03.01
super & override  (0) 2025.03.01
상속 inheritance  (0) 2025.03.01