모던 자바스크립트 Deep Dive: 16장 프로퍼티 어트리뷰트

16장 프로퍼티 어트리뷰트

먼저 프로퍼티와 메소드를 모른다면 10장 객체 리터럴을 다시 공부하고 와주세요.

16.1 내부 슬롯과 내부 메서드

앞으로 살펴볼 프로퍼티 어트리뷰트를 이해하기 위해선 내부 슬롯과 내부 메서드의 개념을 먼저 알아야한다.

내부 슬롯과 내부 메서드는

  • ECMAScript 사양에 등장하는 이중 대괄호([[...]])로 감싼 이름들
  • 자바스크립트 엔진에서 실제로 동작은 하지만 개발자가 직접 접근할 수 없음 (외부로 공개된 객체의 프로퍼티가 아님)

하지만 "일부" 내부 슬롯과 메서드에 한해 간접적으로 접근할 수 있는 수단을 제공하긴 한다.
모든 객체는 [[Prototype]]라는 내부 슬롯을 갖는데 원칙적으로 접근할 수는 없지만 이 슬롯은 __proto__를 통해 간접적으로 접근 가능하다.

const o = {};

o.[[Prototype]] //uncaught SyntaxError : Unexpected token '['
o.__proto__ // Object.prototype

16.2 프로퍼티 어트리뷰트와 프로퍼티 디스크립터 객체

자바스크립트 엔진은 프로퍼티를 생성할 때 프로퍼티의 상태를 나타내는 프로퍼티 어트리뷰트를 기본값으로 자동 정의한다.

프로퍼티 : 값 : [[value]], 갱신 가능 여부 [[Writable]], 열거 가능 여부[[Enumerable]], 재정의 가능 여부[[Configurable]]

const person = {
  name = 'Ahn'
};

//객체의 참조, 프로퍼티 키 전달
console.log(Object.getOwnPropertyDescriptor(person,'name');
//  전달한 프로퍼티 키를 가진 프로퍼티 디스크립터 객체 반환
// {value : 'Ahn', writable : true, enumerable : true, configurable : true}
console.log(Object.getOwnPropertyDescriptor(person,'house');
// 존재하지 않는 프로퍼티 디스크립터를 요구하면 undefined 반환
            
person.age = 20;
            
//객체의 참조 전달
console.log(Object.getOwnPropertyDescriptors(person);
// 모든 프로퍼티 디스크립터 객체 반환
// name : {value : 'Ahn', writable : true, enumerable : true, configurable : true}
// age : {value : 20, writable : true, enumerable : true, configurable : true}

16.3 데이터 프로퍼티와 접근자 프로퍼티

프로퍼티는 데이터 프로퍼티와 접근자 프로퍼티로 구분할 수 있다.
각 프로퍼티를 알아보자.

데이터 프로퍼티

프로퍼티 어트리뷰트프로퍼티 디스크립터 객체의 프로퍼티설명

[[value]] value - 프로퍼티 키를 통해 값에 접근하면 반환되는 값
-키를 통해 값을 변경하면 [[value]]에 값이 재할당됨
- 프로퍼티가 없으면 프로퍼티 동적 생성하고 [[value]] 값에 할당
[[Writable]] writable - 프로퍼티 값의 변경가능 여부 (불리언)
- false인 경우 [[value]] 값을 변경할 수 없는 읽기 전용 프로퍼티
[[Enumerable]] enumerable - 프로퍼티 열거 가능 여부 (불리언)
- false인 경우 for...in, Object.keys 등 사용 불가
[[Configurable]] configurable - 프로퍼티 재정의 가능 여부 (불리언)
- false인 경우 해당 프로퍼티 삭제, 프로퍼티 값 변경 불가
단, [[writable]]이 true인 경우 value 변경 가능, [[writable]]을 false로 변경 가능

접근자 프로퍼티

자체적으로 값을 갖지 않고 다른 데이터 프로퍼티의 값을 읽거나 저장할 때 사용하는 접근자 함수로 구성됨

프로퍼티 어트리뷰트프로퍼티 디스크립터 객체의 프로퍼티설명

[[Get]] get - 접근자 프로퍼티를 통해 데이터 값을 읽을 때 호출됨
- 접근자 프로퍼티 키로 접근하면 getter함수 호출, 결과 프로퍼티 반환
[[Set]] set - 접근자 프로퍼티를 통해 데이터 값을 저장할 때 호출됨
- 접근자 프로퍼티 키로 접근하면 setter함수 호출, 결과 프로퍼티 저장
[[Enumerable]] enumerable - 데이터 프로퍼티와 같음
[[Configurable]] configurable - 데이터 프로퍼티와 같음
const person = {
    firstName : 'Meerkat',
    lastName : 'Ahn',

    get fullName(){
        return `${this.firstName} ${this.lastName}`;
    },
    set fullName(name){
        [this.firstName, this.lastName] = name.split(' '); 
    }
}

console.log(person.firstName + ' ' + person.lastName);

person.fullName = 'Meer Ahn';
console.log(person); // { firstName: 'Meer', lastName: 'Ahn', fullName: [Getter/Setter] }

console.log(person.fullName); // Meer Ahn

console.log(Object.getOwnPropertyDescriptor(person, 'firstName'));
//{ value: 'Meer', writable: true, enumerable: true, configurable: true }

console.log(Object.getOwnPropertyDescriptor(person, 'fullName'));
//{ get: [Function: get fullName], set: [Function: set fullName], enumerable: true, configurable: true}

16.4 프로퍼티 정의

프로퍼티 정의는 두가지 경우를 말한다.

  • 새로운 프로퍼티를 추가하면서 프로퍼티 어트리뷰트를 명시적으로 정의
  • 기존 프로퍼티의 프로퍼티 어트리뷰트를 재정의
    Object.defineProperty(객체의 참조, 프로퍼티 키, 프로퍼티 디스크립터 객체)를 사용하면 정의가 가능하다.

프로퍼티 디스크립터 객체의 경우 프로퍼티 일부 생략이 가능한데 각 프로퍼티는 아래와 같은 기본값이 정의된다.

프로퍼티 디스크립터 객체의 프로퍼티대응하는 프로퍼티 어트리뷰트생략했을 때의 기본값

value [[Value]] undefined
get [[Get]] undefined
set [[Set]] undefined
writable [[Writable]] false
enumerable [[Enumerable]] false
configurable [[Configurable]] false
const person = {};

//<데이터 프로퍼티 정의>
Object.defineProperty(person, 'firstName', {
    value : 'Meerkat',
    writable : true,
    enumerable : true,
    configurable : true
});

Object.defineProperty(person, 'lastName', {
    value : 'Lee'
})

console.log(Object.getOwnPropertyDescriptor(person, 'firstName'));
//{ value: 'Meerkat', writable: true, enumerable: true, configurable: true }
console.log(Object.getOwnPropertyDescriptor(person, 'lastName'));
//{value: 'Lee',writable: false,enumerable: false,configurable: false}

console.log(Object.keys(person));  // [ 'firstName' ] lastName은 enumerable: false라 나타나지 않음

person.lastName = 'Kim'; // 변경 불가 writable: false, 에러는 안남

delete person.lastName; // 삭제 불가 configurable: false, 에러는 안남

//<접근자 프로퍼티 정의>
Object.defineProperty(person, 'fullName', {
    get(){
        return `${this.firstName} ${this.lastName}`
    },
    set(name){
        [this.firstName,this.lastName] = name.split(' ');
    },
    enumerable: true,
    configurable : true
})

만약 여러 개의 프로퍼티를 한 번에 정의하고 싶다면 Object.defineProperties를 사용해보자.

Object.defineProperties(person, {
    firstName : {
        value : 'Meerkat',
        writable : true,
        enumerable : true,
        configurable : true
    },
    lastName : {
        value : 'Ahn',
        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
    }
})

16.5 객체 변경 방지

자바스크립트는 객체의 변경을 방지하는 다양한 메서드를 제공한다.
각 메서드들은 변경을 금지하는 강도가 다르다.

구분메서드프로퍼티 추가프로퍼티 삭제프로퍼티 값 읽기프로퍼티 값 쓰기프로퍼티 어트리뷰트 재정의

객체 확장 금지 Object.preventExtensions X O O O O
객체 밀봉 Object.seal X X O O X
객체 동결 Object.freeze X X O X X

객체 확장 금지

Object.preventExtensions는 객체의 추가를 금지한다. (삭제, 변경은 가능)
동적 추가와 Object.defineProperty 모두 금지
확장이 가능한지 궁금하다면 Object.isExtensible()을 통해 알 수 있다.

const person = { name : 'Ahn'};

console.log(Object.isExtensible(person)); //true

Object.preventExtensions(person);

console.log(Object.isExtensible(person)); //false

person.name = 'Kim'
console.log(person); // { name: 'Kim' }

delete person.name;
console.log(person); //{}

console.log(Object.getOwnPropertyDescriptor(person,'name'))
//{ value: 'Kim', writable: true, enumerable: true, configurable: true }

객체 밀봉

Object.seal은 프로퍼티 추가, 삭제, 재정의를 금지한다. (읽기와 쓰기만 가능)
밀봉된 객체인지 여부는 Object.isSealed()로 확인 가능하다.

const person = { name : 'Ahn'};

console.log(Object.isSealed(person)); //false

Object.seal(person);

console.log(Object.isSealed(person)); //true

person.name = 'Kim'
console.log(person); // { name: 'Kim' }

console.log(Object.getOwnPropertyDescriptor(person,'name'))
//{ value: 'Kim', writable: true, enumerable: true, configurable: false }

객체 동결

Object.freeze는 객체를 동결해 추가, 삭제, 재정의 금지, 값 갱신을 금지한다.(읽기만 가능)
Object.isFrozen() 메서드로 확인 가능하다.

const person = { name : 'Ahn'};

console.log(Object.isFrozen(person)); //false

Object.freeze(person);

console.log(Object.isFrozen(person)); //true

console.log(Object.getOwnPropertyDescriptor(person,'name'))
//{value: 'Ahn', writable: false, enumerable: true, configurable: false}

불변 객체

변경이 불가능한 읽기 전용의 객체이다.
앞에서 본 메서드들은 얕은 변경 방지(shallow only)로 직속 프로퍼티만 변경이 방지되고 중첩 객체까지는 영향을 주지는 못해서
만약 Object.freeze로 객체를 동결해도 중첩 객체까지는 동결이 불가능하다.

const person = { 
    name : 'Ahn',
    address : {city :"Seoul"}
};

Object.freeze(person);

console.log(Object.isFrozen(person)); //true

console.log(Object.isFrozen(person.address)); //false

person.address.city = 'Busan';
console.log(person); //{ name: 'Ahn', address: { city: 'Busan' } }

그렇기 때문에 중첩 객체까지 동결하기 위해선 객체를 값으로 갖는 모든 프로퍼티에 대해 재귀적으로 Object.freeze()를 호출해야한다.

function deepFreeze(target){
    if(target && typeof target === 'object' && !Object.isFrozen(target)){
        Object.freeze(target);
        Object.keys(target).forEach(key => deepFreeze(target[key]));
    }
    return target;
}

const person = { 
    name : 'Ahn',
    address : {city :"Seoul"}
};

deepFreeze(person);

console.log(Object.isFrozen(person)); //true

console.log(Object.isFrozen(person.address)); //true

person.address.city = 'Busan';
console.log(person); //{ name: 'Ahn', address: { city: 'Seoul' } }