Javascript

[모자딥]프로퍼티 어트리뷰트 객체 변경 방지

index.ys 2023. 11. 25. 23:52

예제 16.09

const person = {};

Object.defineProperties(person, {
    // 데이터 프로퍼티 정의
    firstName: {
        value: 'Ungmo',
        writable: true,
        enumerable: true,
        configurable: true
    },
    lastName: {
        value: 'Lee',
        writable: true,
        enumerable: true,
        configurable: true
    },
    // 접근자 프로퍼티 정의
    fullName: {
        // getter 함수
        get() {
            return `${this.firstName} ${this.lastName}`;
        },
        // setter 함수
        set(name) {
            //console.log("🚀 ~ file: 16.09.js:26 ~ set ~ name:", name)
            [this.firstName, this.lastName] = name.split(' ');
        },
        enumerable: true,
        configurable: true
    }
});

person.fullName = '니가 최고야';
console.log(person); // {firstName: "니가", lastName: "최고야"}
console.log(person.fullName);// 니가 최고야
console.log(Object.getOwnPropertyDescriptors(person))

예제 16.10

  • Object.isExtensible()메서드는 객체가 확장이 금지되었는지 아닌지 판단하는 메서드 true or false
  • 확장가능 = true, 확장 불가능 = false
  • Object.preventExtensions() 메서드는 객체를 확장 금지시키는 메서드 객체에 프로퍼티를 추가하는건 불가능하지만 delete는 가능.
  • Object.defineproprety() 메서드로 프로퍼티를 정의하면서 객체를 확장하는 것도 불가능.
const person = { name: 'Lee' };
const animal = { name: 'dog' }
// person 객체는 확장이 금지된 객체가 아니다.
console.log(Object.isExtensible(person)); // true
console.log(Object.isExtensible(animal)); // true

// person 객체의 확장을 금지하여 프로퍼티 추가를 금지한다.
Object.preventExtensions(person);

// person 객체는 확장이 금지된 객체다.
console.log(Object.isExtensible(person)); // false
// animal 객체는 preventExtensions메서드로 확장을 금지 시키지않음
console.log(Object.isExtensible(animal)); // true

// 프로퍼티 추가가 금지된다.
person.age = 20; // 무시. strict mode에서는 에러
console.log(person); // {name: "Lee"}

// 객체 확장이 금지되지 않았으므로 프로퍼티 추가도 가능
animal.tail = true
console.log(animal)
// {name : 'dog' , animal : true}
delete animal.name
console.log(animal)
// {tail : true}

// 프로퍼티 추가는 금지되지만 삭제는 가능하다.
delete person.name;
console.log(person); // {}

// 프로퍼티 정의에 의한 프로퍼티 추가도 금지된다.
Object.defineProperty(person, 'age', { value: 20 });
// TypeError: Cannot define property age, object is not extensible