프로퍼티 어트리뷰트 16

내부 슬롯과 내부 메서드

모든 객체는 [[Prototype]] 이라는 내부 슬롯을 갖는다.
내부 슬롯은 자바스크립트 엔진의 내부 로직이므로 원칙적으로 직접 접근할 수 없지만 [[Prototype]] 내부 슬롯의 경우, __proto__ 를 통해 간접적으로 접근할 수 있다.

const o = {};
o.[[Prototype]] // → Uncaught SyntaxError
o.__proto__ // → Object.prototype

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

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

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

데이터 프로퍼티

프로퍼티 어트리뷰트 프로퍼티 디스크립터 객체의 프로퍼티
[[Value]] value
[[Writable]] writable
[[Enumerable]] enumerable
[[Configurable]] configurable

접근자 프로퍼티

접근자 프로퍼티는 자체적으로는 값을 갖지 않고 다른 데이터 프로퍼티의 값을 읽거나 저장할 때 사용하는 접근자 함수로 구성된 프로퍼티다.
접근자 함수는 getter/setter 함수라고도 부른다.
접근자 프로퍼티는 getter와 setter 함수를 모두 정의할 수도 있고 하나만 정의할 수도 있다.

프로퍼티 어트리뷰트 프로퍼티 디스크립터 객체의 프로퍼티
[[Get]] get
[[Set]] set
[[Enumerable]] enumerable
[[Configurable]] configurable
const person = {
    // 데이터 프로퍼티
    firstName:'mary',
    lastName:'go',

    // fullName은 접근자 함수로 구성된 접근자 프로퍼티다.
    // getter 함수
    get fullName(){
        return `${this.firstName} ${this.lasName}`;
    },
    // setter 함수    
    set fullName(name){
        [this.firstName, this.lastName] = name.split(' ');
    }
};
console.log(person.firstName+' '+person.lastName);

person.fullName = 'Dean James';
console.log(person);
console.log(person.fullName);

// 데이터 프로퍼티는 [[Value]],[[Writable]],[[Enumerable]],[[Configurable]] 프로퍼티 어트리뷰트를 갖는다.
let descriptor = Object.getOwnPropertyDescriptor(person, 'firstName');
console.log(descriptor);

// 접근자 프로퍼티는 [[Get]],[[Set]],[[Enumerable]],[[Configurable]] 프로퍼티 어트리뷰트를 갖는다.
descriptor = Object.getOwnPropertyDescriptor(person, 'fullName');
console.log(descriptor);

프로토타입
프로토타입은 어떤 객체의 상위(부모) 객체의 역할을 하는 객체다.
프로토타입은 하위(자식) 객체에게 자신의 프로퍼티와 메서드를 상속한다.
프로토타입 객체의 프로퍼티나 메서드를 상속받은 하위 객체는 자신의 프로퍼티 또는 메서드인 것처럼 자유롭게 사용할 수 있다.

접근자 프로퍼티와 데이터 프로퍼티를 구별하는 방법

// 일반 객체의 __proto__는 접근자 프로퍼티다.
Object.getOwnPropertyDescriptor(Object.prototype, '__proto__');

// 함수 객체의 prototype은 데이터 프로퍼티다.
Object.getOwnPropertyDescriptor(function(){}, 'prototype');

프로퍼티 정의

Object.defineProperty 메서드를 사용하면 프로퍼티의 어트리뷰트를 정의할 수 있다.
인수로는 객체의 참조와 데이터 프로퍼티의 키인 문자열, 프로퍼티 디스크립터 객체를 전달한다.

const person = {};
Object.defineProperty(person, 'firstName', {
    value:'mary',
    writable:true,
    enumerable:true,
    configurable:true
});
Object.defineProperty(person, 'lastName', {
    value:'lee'
});

let descriptor = Object.getOwnPropertyDescriptor(person, 'firstName');
console.log('firstName', descriptor);

descriptor = Object.getOwnPropertyDescriptor(person, 'lastName');
console.log('lastName', descriptor);

console.log(Object.keys(person));

person.lastName = 'Kim';

// [[Configurable]] 값이 false인 경우 해당 프로퍼티를 삭제할 수 없다.
delete person.lastName;

// [[Configurable]] 값이 false인 경우 해당 프로퍼티를 재정의할 수 없다.
descriptor = Object.getOwnPropertyDescriptor(person, 'lastName');
console.log('lastName', descriptor);

Object.defineProperty(person, 'fullName', {
    get(){
        return `${this.firstName} ${this.lastName}`;
    },
    set(name){
        [this.firstName, this.lastName] = name.split(' ');
    },
    enumerable: true,
    configurable:true
});

descriptor = Object.getOwnPropertyDescriptor(person, 'fullName');
console.log('fullName', descriptor);

person.fullName = 'Dean James';
console.log(person);

Object.defineProperties 메서드를 사용하면 여러 개의 프로퍼티를 한 번에 정의할 수 있다.

const person = {};
Object.defineProperties(person, {
    firstName:{
        value:'mary',
        writable:true,
        enumerable:true,
        configurable:true
    },
    lastName:{
        value:'go',
        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
    }    
});
person.fullName = 'Dean James';
console.log(person);

객체 변경 방지

구분 메서드 프로퍼티 추가 프로퍼티 삭제 프로퍼티 값 읽기 프로퍼티 값 쓰기 프로퍼티 어트리뷰트 재정의
객체 확장 금지 Object.preventExtensions x o o o o
객체 밀봉 Object.seal x x o o x
객체 동결 Object.freeze x x o x x

객체 확장 금지

Object.preventExtensions 메서드는 객체의 확장을 금지한다.
확장이 금지된 객체는 프로퍼티 추가가 금지된다.
확장이 가능한 객체인지 여부는 Object.isExtensible 메서드로 확인할 수 있다.

const person = {name:'lee'};
console.log(Object.isExtensible(person)); // true

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

person.age = 30;
console.log(person); // {name:'lee'}

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

Object.defineProperty(person, 'age', {value:20});

객체 밀봉

Object.seal 메서드는 객체를 밀봉한다.
밀봉된 객체는 읽기와 쓰기만 가능하다.
밀봉된 객체인지 여부는 Object.isSealed 메서드로 확인할 수 있다.

const person = {name:'lee'};
console.log(Object.isSealed(person)); // false

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

console.log(Object.getOwnPropertyDescriptors(person));

person.age = 30;
console.log(person); // {name:'lee'}

// 프로퍼티 삭제가 금지된다.
delete person.name;
console.log(person); // {name:'lee'}

// 프로퍼티 값 갱신은 가능하다.
person.name = 'Kim';
console.log(person); // {name:'Kim'}

// 프로퍼티 어트리뷰트 재정의가 금지된다.
Object.defineProperty(person, 'name', {configurable:true});

객체 동결

Object.freeze 메서드는 객체를 동결한다.
동결된 객체는 읽기만 가능하다.
동결된 객체인지 여부는 Object.isFrozen 메서드로 확인할 수 있다.

const person = {name:'lee'};
console.log(Object.isFrozen(person)); // false

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

console.log(Object.getOwnPropertyDescriptors(person));

person.age = 30;
console.log(person); // {name:'lee'}

// 프로퍼티 삭제가 금지된다.
delete person.name;
console.log(person); // {name:'lee'}

// 프로퍼티 값 갱신이 금지된다.
person.name = 'Kim';
console.log(person); // {name:'lee'}

// 프로퍼티 어트리뷰트 재정의가 금지된다.
Object.defineProperty(person, 'name', {configurable:true});

불변 객체

변경방 메서드들은 얕은 변경 방지로 직속 프로퍼티만 변경이 방지되고 중첩 객체까지는 영향을 주지 못한다.
따라서 Object.freeze 메서드로 객체를 동결하여도 중첩 객체까지 동결할 수 없다.
객체의 중첩 객체까지 동결하여 변경이 불가능한 읽기 전용의 불변 객체를 구현하려면 객체를 값으로 갖는 모든 프로퍼티에 대해 재귀적으로 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:'lee',
    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:'lee', address:{city:'seoul'}};