프로퍼티 어트리뷰트

heejung·2022년 3월 30일
0

deep dive

목록 보기
14/20

내부 슬롯 & 내부 메소드

자바스크립트 엔진의 구현 알고리즘을 설명하기 위해 ECMAScript 사양에서 사용하는 의사 프로퍼티(pseudo property)와 의사 메소드(pseudo method)이다.

  • 자바스크립트 엔진의 내부 로직 => 개발자가 직접적으로 접근 불가
  • 일부 내부 슬롯, 내부 메소드에 한해 간접적으로 접근 가능

모든 객체는 [[Prototype]] 이라는 내부 슬롯을 가지며, 원칙적으로는 직접 접근할 수 없지만 __proto__ 를 통해 간접적으로 접근할 수 있다.

const o = {};

o.[[Prototype]] // Uncaught SyntaxError (접근 불가)
o.__proto__ // Object.prototype (접근 가능)



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

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

프로퍼티 어트리뷰트

자바스크립트 엔진이 관리하는 내부 상태 값인 내부 슬롯이다.

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

프로퍼티 어트리뷰트에 직접 접근할 수는 없지만, Object.getOwnPropertyDescriptor 메소드를 사용해 간접적으로 확인할 수 있다.

Object.getOwnPropertyDescriptor(객체, '프로퍼티 키')
  • 하나의 프로퍼티에 대해 프로퍼티 디스크립터 객체 반환
  • ES8에서 도입된 Object.getOwnPropertyDescriptors => 모든 프로퍼티에 대해 반환
const person = {
  name: 'Lee'
};

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

person.age = 20;

console.log(Object.getOwnPropertyDescriptors(person));
/*
{
  name: {value: "Lee", writable: true, enumerable: true, configurable: true},
  age: {value: 20, writable: true, enumerable: true, configurable: true}
}
*/



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

데이터 프로퍼티

  • 키와 값으로 구성된 일반적인 프로퍼티
프로퍼티 어트리뷰트프로퍼티 디스크립터 객체의 프로퍼티설명
[[Value]]value프로퍼티 키를 통해 프로퍼티 값에 접근하면 반환되는 값
[[Writable]]writable- 프로퍼티 값의 변경 여부 (불리언 값)
- true로 초기화
- false인 경우, [[Vavlue]] 값을 변경할 수 없는 읽기 전용 프로퍼티가 됨
[[Enumerable]]enumerable- 프로퍼티의 열거 가능 여부 (불리언 값)
- true로 초기화
- false인 경우, for ... in/Object.keys 메소드 등으로 열거 X
[[Configurable]]configurable- 프로퍼티의 재정의 가능 여부 (불리언 값)
- true로 초기화
- false인 경우, 프로퍼티의 삭제/프로퍼티 어트리뷰트 값 변경 금지

접근자 프로퍼티

  • 자체적으로 값을 갖지 않고, 다른 데이터 프로퍼티의 값을 읽거나 저장할 때 호출되는 접근자 함수로 구성된 프로퍼티
프로퍼티 어트리뷰트프로퍼티 디스크립터 객체의 프로퍼티설명
[[Get]]get접근자 프로퍼티로 데이터 프로퍼티 값을 읽을 때 호출되는 접근자 함수
[[Set]]set접근자 프로퍼티로 데이터 프로퍼티 값을 저장할 때 호출되는 접근자 함수
[[Enumerable]]enumerable데이터 프로퍼티의 [[Enumerable]]와 동일
[[Configurable]]configurable데이터 프로퍼티의 [[Configurable]]와 동일

접근자 함수는 getter/setter 함수라고도 부른다.
접근자 프로퍼티는 getter 와 setter 함수를 모두정의할 수도 있고 하나만 정의할 수도 있다.

const person = {
  // 데이터 프로퍼티
  firstName: 'Ungmo',
  lastName: 'Lee;,
  
  // fullName => 접근자 함수로 구성된 접근자 프로퍼티
  get fullName() { // getter 함수
    return `${this.firstName} ${this.lastName}`;
  },
    
  set fullName(name) { // setter 함수
    [this.firstName, this.lastName] = name.split(' ');
  }
};

// 데이터 프로퍼티를 통한 프로퍼티 값 참조
console.log(person.firstName + ' ' + person.lastName); // Ungmo Lee

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

// 접근자 프로퍼티를 통한 프로퍼티 값 참조
console.log(person.fullName);

// firstName => 데이터 프로퍼티
let descriptor = Object.getOwnPropertyDescriptor(person, 'firstName');
console.log(descriptor);
// {value: "Heegun", writable: true, enumerable: true, configurable: true}

// fullName => 접근자 프로퍼티
descriptor = Object.getOwnPropertyDescriptor(person, 'fullName');
console.log(descriptor);
// {get: f, set: f, enumerable: true, configurable: true}



프로퍼티 정의

새로운 프로퍼티를 추가하면서 프로퍼티 어트리뷰트를 명시적으로 정의 or 기존 프로퍼티의 프로퍼티 어트리뷰트를 재정의하는 것을 말한다.

Object.defineProperty(객체, '프로퍼티 키', 프로퍼티 디스크립터 객체)
  • 한번에 하나의 프로퍼티만 정의 가능
  • Object.defineProperties 로 여러개 정의 가능
const person = {};

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

// 디스크립터 객체 프로퍼티 누락 => undefined, false가 기본값
Object.defineProperty(person, 'lastName', {
  value: 'Lee'
});

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

descriptor = Object.getOwnPropertyDescriptor(person, 'lastName');
console.log(descriptor);
// {value: "Lee", writable: false, enumerable: false, configurable: false}



객체 변경 방지

객체 확장 금지

  • Object.preventExtenstions 사용
  • 객체 프로퍼티 추가 금지 (프로퍼티 동적 추가, Object.defineProperty 모두 금지)
  • 확장 가능 객체인지 여부는 Object.isExtensible 로 확인 가능

객체 밀봉

  • Object.seal 사용
  • 프로퍼티 추가 및 삭제, 프로퍼티 어트리뷰트 재정의 금지
  • 밀봉된 객체는 읽기/쓰기만 가능
  • 밀봉된 객체인지 여부는 Object.isSealed 로 확인 가능

객체 동결

  • Object.freeze 사용
  • 프로퍼티 추가 및 삭제, 프로퍼티 어트리뷰트 재정의 금지, 프로퍼티 값 갱신 금지
  • 동결된 객체는 읽기만 가능
  • 동결된 객체인지 여부는 Object.isFrozen 으로 확인 가능

불변 객체

위의 변경 방지 메소드들은 얕은 변경 방지로, 직속 프로퍼티만 변경 방지되고 중첩 객체까지는 영향을 주지 못한다. 중첩 객체까지 동결하려면 객체를 값으로 갖는 모든 프로퍼티에 대해 재귀적으로 Object.freeze 를 호출해야 한다.

profile
프론트엔드 공부 기록

0개의 댓글