본문 바로가기

Javascript/모던 자바스크립트 DeepDive

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

내부 슬롯과 내부 메서드

  • 내부 슬롯 internal slot과 내부 메서드 internal method는 자바스크립트 엔지의 구현 알고리즘을 설명하기 위해 ECMAScript 사양에 사용하는 의사 프로퍼티 pseudo property와 의사 메서드 pseudo method
  • ECMASciprt 사양에 등장하는 이중 대괄호([[...]])로 감싼 이름에 해당
  • 자바스크립트의 내부 로직이므로 원칙적으로 내부 슬롯과 내부 메서드에 직접적으로 접근하거나 호출할 수 있는 방법을 제공하지는 않음 (일부에 한하여 간접적으로 접근 가능)
const o = {};
// 내부 슬롯은 직접 접근 불가능
o.[[Prototype]] // SyntaxError
// 일부에 한해 간접적으로 접근 가능
o.__proto__; // Object.prototype

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

  • 자바스크립트 엔진은 프로퍼티를 생성할 때, 프로퍼티의 상태를 나타내는 프로퍼티 어트리뷰트를 기본값으로 자동 정의
  • 프로퍼티 어트리뷰트는 직접 접근할 수 는 없지만 Object.getOwnPropertyDescriptor 메서드를 사용하여 간접적으로 확인 가능
  • 내부 상태 값 meta-property: 프로퍼티 상태
    • [[Value]]: 프로퍼티 값
    • [[Writable]]: 값의 갱신 여부
    • [[Enumerable]]: 열거 가능 여부
    • [[Configurable]]: 재정의 가능 여부
const person = {
  name: "Jin",
};

// Object.getOwnPropertyDescriptor 메서드는 프로퍼티 어트리뷰트 정보를 제공하는 프로퍼티 디스크립터 객체 반환
console.log(Object.getOwnPropertyDescriptor(person, "name")); 
// { value: 'Jin', writable: true, enumerable: true, configurable: true }
const person = {
  name: "Jin",
};
person.location = "Seoul";

// ES8에 도입된 Object.getOwnPropertyDescriptors 메서드는 모든 프로퍼티 어트리뷰트 정보 제공
console.log(Object.getOwnPropertyDescriptors(person));
// {
//   name: {
//     value: 'Jin',
//     writable: true,
//     enumerable: true,
//     configurable: true
//   },
//   location: {
//     value: 'Seoul',
//     writable: true,
//     enumerable: true,
//     configurable: true
//   }
// }

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

  • 데이터 프로퍼티 data property: 키와 값으로 구성된 일반적인 프로퍼티
  • 접근자 프로퍼티 accessor property: 자체적으로 값을 갖지 않고 다른 데이터 프로퍼티의 값을 읽거나 저장할 때 호출되는 접근자 함수 accessor function으로 구성된 프로퍼티

데이터 프로퍼티

프로퍼티
어트리뷰트
프로퍼티 디스크립터 객체의 프로퍼티 설명
[[Value]] value - 프로퍼티 키를 통해 프로퍼티 값에 접근하면 반환되는 값
- 프로퍼티 키를 통해 프로퍼티 값을 변경하면 [[Value]]에 값을 재할당. 이때 프로퍼티가 없으면 프로퍼티를 동적 생성하고 생성된 프로퍼티의 [[Value]]에 값저장
[[Writable]] writable - 프로퍼티 값의 변경 가능 여부를 나타내며 불리언 값
- [[Writable]] 값이 false인 경우 해당 프로퍼티의  [[Value]] 값을 변경할 수 없는 읽기 전용 프로퍼티가 됨
[[Enumerable]] enumerable - 프로퍼티의 열거 가능 여부를 나타내며 불리언 값
- [[Enumerable]] 값이 false인 경우 해당 프로퍼티는 for ... in 문이나 Object.keys 메서드 등으로 열거 불가능
[[Configurable]] configurable - 프로퍼티의 재정의 가능 여부를 나타내며 불리언 값
- [[Configurable]] 값이 false인 경우 해당 프로퍼티의 삭제, 프로퍼티 어트리뷰트 값의 변경이 금지 됨. 단, [[Writable]] 값이 true인 경우 [[Value]]의 변경과 [[Writable]]을 false로 변경하는 것은 허용

접근자 프로퍼티

  • 자체적으로는 값을 갖지 않고 다른 데이터 프로퍼티의 값을 읽거나 저장할 때 사용하는 접근자 함수로 구성된 프로퍼티
  • 접근자 함수는 getter / setter 함수라고도 부름
프로퍼티
어트리뷰트
프로퍼티 디스크립터 객체의 프로퍼티 설명
[[Get]] get 접근자 프로퍼티를 통해 데이터 프로퍼티 값을 읽을 때 호출되는 접근자 함수. 즉, 접근자 프로퍼티 키로 프로퍼티 값에 접근하면 프로퍼티 어트리뷰트 [[Get]]의 값, 즉 getter 함수가 호출되고 그 결과가 프로퍼티 값으로 반환
[[Set]] set - 접근자 프로퍼티를 통해 데이터 프로퍼티 값을 저장할 때 호출되는 접근자 함수. 즉, 접근자 프로퍼티 키로 프로퍼티 값을 저장하면 프로퍼티 어트리뷰트 [[Set]]의 값, 즉 setter 함수가 호출되고 그 결과가 프로퍼티 값으로 반환
[[Enumerable]] enumerable - 프로퍼티의 열거 가능 여부를 나타내며 불리언 값
- [[Enumerable]] 값이 false인 경우 해당 프로퍼티는 for ... in 문이나 Object.keys 메서드 등으로 열거 불가능
[[Configurable]] configurable - 프로퍼티의 재정의 가능 여부를 나타내며 불리언 값
- [[Configurable]] 값이 false인 경우 해당 프로퍼티의 삭제, 프로퍼티 어트리뷰트 값의 변경이 금지 됨
const person = {
  // 데이터 프로퍼티
  firstName: "HongYeop",
  lastName: "Jin",

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

// 데이터 프로퍼티를 통한 프로퍼티 값의 참조 (setter함수 호출)
console.log(person.firstName + " " + person.lastName); // HongYeop Jin

// 접근자 프로퍼티를 통한 프로퍼티 값의 저장
person.fullName = "Ungmo Lee";
console.log(person); // { firstName: 'Ungmo', lastName: 'Lee', fullName: [Getter/Setter] }

// 접근자 프로퍼티를 통한 프로퍼티 값의 참조 (getter함수 호출)
console.log(person.fullName); // Ungmo Lee

// 데이터 프로퍼티 어트리뷰트 확인
let descriptor = Object.getOwnPropertyDescriptor(person, "firstName");
console.log(descriptor);
// {value: 'Ungmo', writable: true, enumerable: true, configurable: true}

// 접근자 프로퍼티 어트리뷰트 확인
descriptor = Object.getOwnPropertyDescriptor(person, "fullName");
console.log(descriptor);
// {get: [Function: get fullName], set: [Function: set fullName], enumerable: true, configurable: true}
// 일반 객체의 __proto__는 접근자 프로퍼티
Object.getOwnPropertyDescriptor(Object.prototype, "__proto__");
// {enumerable: false, configurable: true, get: ƒ, set: ƒ}

// 함수 객체의 prototype은 데이터 프로퍼티
Object.getOwnPropertyDescriptor(function () {}, "prototype");
// {value: {…}, writable: true, enumerable: false, configurable: false}

프로퍼티 정의

  • Object.defineProperty 메서드를 사용하여 프로퍼티의 어트리뷰트를 정의 가능
  • Object.defineProperties 메서드를 사용하여 여러 개의 프로퍼티 한 번에 정의 가능
const person = {};

Object.defineProperty(person, "firstName", {
  value: "HongYeop",
  writable: true,
  enumerable: true,
  configurable: true,
});

Object.defineProperty(person, "lastName", {
  value: "Jin",
});

let descriptor = Object.getOwnPropertyDescriptor(person, "firstName");
console.log(descriptor);
// {value: 'HongYeop', writable: true, enumerable: true, configurable: true}

// 디스크립터 객체의 프로퍼티를 누락시키면 undefined, false가 기본 값
descriptor = Object.getOwnPropertyDescriptor(person, "lastName");
console.log(descriptor); // {value: 'Jin', writable: false, enumerable: false, configurable: false}

// [[Enumerable]] 값이 false인 경우
// 해당 프로퍼티는 for ... in 문이나 Object.keys 등으로 열거 불가능
// lastName 프로퍼티는 [[Enumerable]] 값이 false이므로 열거되지 않음
console.log(Object.keys(person)); // ['firstName']

// [[Writable]] 값이 false인 경우 해당 프로퍼티의 [[Value]] 값을 변경할 수 없음
// lastName 프로퍼티는 [[Writable]] 값이 false이므로 값을 변경할 수 없음
// 이때 값을 변경하면 에러는 발생하지 않고 무시
person.lastName = "Park";
console.log(person); // {firstName: 'HongYeop', lastName: 'Jin'} lastName이 변경되지 않음

// [[Configurable]] 값이 false인 경우 해당 프로퍼티를 삭제할 수 없음
// lastName 프로퍼티는 [[Configurable]] 값이 false이므로 값을 삭제할 수 없음
// 이떄 프로퍼티를 삭제하면 에러는 발생하지 않고 무시
delete person.lastName;
console.log(person); // {firstName: 'HongYeop', lastName: 'Jin'} lastName이 삭제되지 않음

// [[Configurable]] 값이 false인 경우 해당 프로퍼티를 재정의할 수 없음
// Object.defineProperty(person, "lastName", { enumerable: true });
// Uncaught TypeError: Cannot redefine property: lastName

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

descriptor = Object.getOwnPropertyDescriptor(person, "fullName");
console.log("fullName", descriptor); // fullName {enumerable: true, configurable: true, get: ƒ, set: ƒ}

person.fullName = "Ungmo Lee";
console.log(person); // {firstName: 'Ungmo', lastName: 'Jin'}
const person = {};

Object.defineProperties(person, {
  // 데이터 프로퍼티 정의
  firstName: {
    value: "HongYeop",
    writable: true,
    enumerable: true,
    configurable: true,
  },
  lastName: {
    value: "Jin",
    writable: true,
    enumerable: true,
    configurable: true,
  },
  // 접근자 프로퍼티 정의
  fullName: {
    // getter 함수
    get() {
      return `${this.firstName} ${this.lastName}`;
    },
    // setter 함수
    set(name) {
      [this.firstName, this.lastName] = name.split(" ");
    },
    enumerable: true,
    configurable: true,
  },
});

person.fullName = "UngMo Lee";
console.log(person); // {firstName: 'UngMo', lastName: 'Lee'}

객체 변경 방지

  • 객체는 변경 가능한 값이므로 재할당 없이 직접 변경할 수 있음
  • 자바스크립트는 객체의 변경을 방지하는 다양한 메서드 제공
구분 메서드 프로퍼티
추가
프로퍼티
삭제
프로퍼티
값 읽기
프로퍼티
값 쓰기
프로퍼티 어트리뷰트 재정의
객체 확장 금지 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: "Jin" };

// person 객체는 확장 가능 객체
console.log(Object.isExtensible(person)); // true

// person 객체 확장 금지
Object.preventExtensions(person);

// person 객체는 확장 불가능 객체
console.log(Object.isExtensible(person)); // false

// 프로퍼티 추가 금지됨
person.age = 29; // 무시 strict mode에서는 에러
console.log(person); // { name: 'Jin' }

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

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

객체 밀봉

  • Object.seal 메서드는 객체를 밀봉
  • 객체 밀봉이란 프로퍼티 추가 및  삭제와 프로퍼티 어트리뷰트 재정의 금지
  • 즉, 밀봉된 개체는 읽기와 쓰기만 가능
  • 밀봉 여부는 Object.isSealed 메서드로 확인 가능
const person = { name: "Jin" };

// person 객체는 밀봉안된 객체
console.log(Object.isSealed(person)); // true

// person 객체 밀봉
Object.seal(person);

// person 객체는 밀봉된 객체
console.log(Object.isSealed(person)); // false

// 밀봉된 객체는 configurable이 false
console.log(Object.getOwnPropertyDescriptors(person));
// {name: {value: 'Jin', writable: true, enumerable: true, configurable: false}}

// 프로퍼티 추가 금지됨
person.age = 29; // 무시 strict mode에서는 에러
console.log(person); // { name: 'Jin' }

// 프로퍼티 삭제 금지
delete person.name; // 무시 strict mode에서는 에러
console.log(person); // { name: 'Jin' }

// 프로퍼티 값 갱신 가능
person.name = "Park";
console.log(person); // { name: 'Park' }

// 프로퍼티 재정의 금지
Object.defineProperty(person, "name", { configurable: true });
// TypeError: Cannot redefine property: name

객체 동결

  • Object.freeze 메서드는 객체를 동결
  • 객체 동결은 프로퍼티 추가 및 삭제와 프로퍼티 어트리뷰트의 재정의 금지, 프로퍼티 값 갱신 금지 의미
  • 즉, 동결된 개체는 읽기만 가능
  • 동결 여부는 Object.isFrozen 메서드로 확인 가능
const person = {
  name: "Jin",
};

// person 객체는 동결된 객체 아님
console.log(Object.isFrozen(person)); // false

// person 객체 동결. 프로퍼티 추가, 삭제, 재정의, 쓰기 금지
Object.freeze(person);

// person 객체는 동결된 객체
console.log(Object.isFrozen(person)); // true

// 동결된 객체는 writable과 configurable이 false
console.log(Object.getOwnPropertyDescriptors(person));
// {name: {value: 'Jin', writable: false, enumerable: true, configurable: false}}

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

// 프로퍼티 삭제 금지
delete person.name; // 무시. strict mode에서는 에러
console.log(person); // { name: 'Jin' }

// 프로퍼티 값 갱신 금지
person.name = "Park"; // 무시. strict mode에서는 에러
console.log(person); // { name: 'Jin' }

// 프로퍼티 어트리뷰트 재정의 금지
Object.defineProperty(person, "name", { configurable: true });
// TypeError: Cannot redefine property: name

불변 객체

  • 지금까지 변경 방지 메서드들은 얕은 변경 방지 shallow only로 직속 프로퍼티만 변경 방지
  • 객체의 중첩 객체까지 동결하여 변경이 불가능한 읽기 전용의 불변 객체를 구현하려면 객체를 값으로 갖는 모든 프로퍼티에 대해서 재귀적으로 Object.freeze 메서드를 호출해야 함
const person = {
  name: "Jin",
  address: { city: "Seoul" },
};

// 얕은 객체 동결
Object.freeze(person);

// 직속 프로퍼티만 동결
console.log(Object.isFrozen(person)); // true
// 중첩 객체는 동결하지 못함
console.log(Object.isFrozen(person.address)); // false
// 객체를 값으로 갖는 모든 프로퍼티에 대해 재귀적으로 Oject.freeze 메서드를 호출하는 함수
function deepFreeze(target) {
  // 객체가 아니거나 동결된 객체는 무시하고 동결되지 않은 객체만 동결
  if (target && typeof target === "object" && !Object.isFrozen(target)) {
    Object.freeze(target);
    // Oject.keys 메서드로 열거 가능한 프로퍼티 키를 배열로 반환,
    // forEach 메서드로 해당 배열을 순회하여 배열의 각 요소에 대해 콜백함수 실행
    Object.keys(target).forEach((key) => deepFreeze(target[key]));
  }
  return target;
}

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

deepFreeze(person);

console.log(Object.isFrozen(person)); // true
// 중첩 객체는 동결하지 못함
console.log(Object.isFrozen(person.address)); // true