[JS]16_프로퍼티 어트리뷰트

니나노개발생활·2021년 9월 17일
0

📖 DeepDive

목록 보기
7/9
post-thumbnail

내부 슬롯과 내부 메서드

  • 프로퍼티 어트리뷰트를 이해하기 위해 먼저 알아보자.
  • ECMAScript 사양에서 사용하는 의사 프로퍼티와 의사 메서드
  • 이중 대괄호([[...]])로 감싼 이름들이 해당된다.
  • 자바스크립트 엔젠의 내부 로직으로 원칙적으로 자바스크립트는 내부 슬롯과 메서드에 직접적으로 접근하거나 호출할 수 있는 방법을 제공하지 않으나 일부 제공한다.

☝🏻 원칙적으로 [[Prototype]] 내부 슬롯의 경우 직접 접근할 수 없지만 간접적으로 접근할 수 있다.

const o = {};
o.[[Prototype]] // 직접 접근 불가
o.__proto__ // 일부 간접적으로 접근할 수 있는 수단을 제공한다.

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

  • 프로퍼티를 생성할 때 프로퍼티의 상태를 나타내는 프로퍼티 어트리뷰트를 기본값으로 자동 정의한다.

☝🏻 프로퍼티의 상태?

  • 프로퍼티의 값(value), 값의 갱신 가능 여부(writable), 열거 가능 여부(enumerable), 재정의 가능 여부(configurable)
  • 프로퍼티 어트리뷰트 : 자바스크립트 엔진이 관리하는 내부 상태 값인 내부 슬롯
    = [[Value]], [[Writable]], [[Enumerable]], [[Configurable]]

🔥 내부 슬롯이기에 직접 접근할 수 없지만 Object.getOwnPropertyDescriptor메서드를 사용해 간접으로 확인이 가능하다

  • 첫 번째 매개변수에는 객체의 참조를 전달하고, 두 번째 매개변수에는 프로퍼티 키를 문자열로 전달한다. >> 프로퍼티 디스크립터 객체를 반환한다.
const person = {
  name : 'lee'
};
console.log(Object.getOwnPropertyDescriptor(person, 'name'));
//{value : 'lee', writable: true, enumerable: true, configurable: true}
  • ES8에 도입된 Object.getOwnPropertyDescriptors 메서드는 모든 프로퍼티의 프로퍼티 어트리뷰트를 제공하는 프로퍼티 디스크립터 객체들을 반환한다.
const person = {
  name : 'lee'
};
// 프로퍼티 동적 생성
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]], [[Writable]], [[Enumerable]], [[Configurable]] 프로퍼티 어트리뷰트를 가지며 이는 프로퍼티를 생성할 때 자동 정의된다.

접근자 프로퍼티

  • 자체적으로는 값을 갖지 않고 다른 데이터 프로퍼티의 값을 읽거나 저장할 때 호출되는 접근자 함수로 구성된 프로퍼티
  • 접근자 프로퍼티는 [[Get]], [[Set]], [[Enumerable]], [[Configurable]] 프로퍼티 어트리뷰트를 갖는다.
  • 접근자 함수는 getter/setter 함수라고도 부르며 접근자 프로퍼티는 이를 모두 정의할 수도 있고 하나만 정의할 수도 있다.

☝🏻메서드 앞에 get, set이 붙는 메서드가 있는데 이것들이 바로 getter, setter 함수이고, getter/setter 함수의 이름 fullName이 접근자 프로퍼티다.

  • 접근자 프로퍼티는 자체적으로 값(프로퍼티 어트리뷰트[[Value]])을 가지지 않으며 다만 데이터 프로퍼티의 값을 읽거나 저장할 때 관여할 뿐이다.
const person = {
  // 데이터 프로퍼티
  firstName : 'ny',
  lastName : 'kim',
  // 접근자 프로퍼티
  // getter 함수
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  },
  // setter 함수
  set fullName(name) {
    [this.firstName, this.lastName] = name.split('');
  }
};

구별법

// 접근자 프로퍼티
Object.getOwnPropertyDescriptor(Object.prototype, '__proto__');
// {get: f, set: f, enumerable: false, configurable: true}

// 데이터 프로퍼티
Object.getOwnPropertyDescriptor(function() {}, 'prototype');
// {value: {...}, writable: true, enumerable: false, configurable: false}    

프로퍼티 정의

  • 새로운 프로퍼티를 추가하면서 프로퍼티 어트리뷰트를 명시적으로 정의하거나 기존 프로퍼티의 프로퍼티 어트리뷰트를 재정의하는 것
  • Object.defineProperty 메서드를 사용하여 정의할 수 있다.
const person = {};

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

Object.defineProperty(person, 'lastName', {
  value: 'kim'
});
  • 여러개의 프로퍼티를 정의하려면 Object.defineProperties
const person = {};

Object.defineProperties(person, {
  // 데이터 프로퍼티의 정의
  firstName: {
    value: 'ny',
 	writable: true,
  	enumerable: true,
  	configurable: true
  },
  lastName: {
    value: 'kim',
 	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
  }
});

객체 변경 방지

  • 객체는 변경 가능한 값이므로 재할당 없이 직접 변경할 수 있다.
    = 프로퍼티를 추가하거나 삭제할 수 있고 프로퍼티 값을 갱신할 수 있다.
    = 프로퍼티 어트리뷰트를 재정의할 수 있다.

객체 확장 금지

  • Object.preventExtensions
  • 확장이 금지된 객체는 프로퍼티 추가가 금지된다 > 삭제는 가능
  • 확장 가능한 객체 확인 여부는 Object.isExtensible 메서드로 확인할 수 있다.
const person = {name: 'lee'};

Object.preventExtensions(person);

person.age = 20; // 무시, strict mode에서는 에러
console.log(person); // {name: 'lee'}

객체 밀봉

  • Object.seal
  • 밀봉된 객체는 읽기와 쓰기만 가능하다 > 갱신은 가능
  • Object.isSealed 메서드로 확인할 수 있다.
const person = {name: 'lee'};

Object.preventExtensions(person);

person.age = 20; // 무시, strict mode에서는 에러
console.log(person); // {name: 'lee'}

delete person.name; // 무시, strict mode에서는 에러
console.log(person); // {name: 'lee'}

객체 동결

  • Object.freeze
  • 동결된 객체는 읽기만 가능하다
  • Object.isFrozen 메서드로 확인할 수 있다.
const person = {name: 'lee'};

Object.preventExtensions(person);

person.age = 20; // 무시, strict mode에서는 에러
console.log(person); // {name: 'lee'}

delete person.name; // 무시, strict mode에서는 에러
console.log(person); // {name: 'lee'}

person.age = 20; // 무시, strict mode에서는 에러
console.log(person); // {name: 'lee'}

person.name = 'kim'; // 무시, strict mode에서는 에러
console.log(person); // {name: 'lee'}

불변 객체

  • 위의 변경 방지 메서드들은 얕은 변경 방지로 직속 프로퍼티만 변경이 방지되고 중첩 객체까지는 영향을 주지 못하여 Object.freeze 메서드로 객체를 동결하여도 중첩 객체까지 동결할 수 없다.
  • 불변 객체를 구현하려면 객체를 값으로 갖는 모든 프로퍼티에 대해 재귀적으로 메서드를 호출해야 한다.
funtion deepFreeze(target) {
  // 객체가 아니거나 동결된 객체는 무시하고 객체이고 동결되지 않은 객체만 동결한다.
  if(target && typeof target === 'object' && !Object.isFrozen(target)) {
    Object.freeze(target);
    // 모든 프로퍼티를 순회하며 재귀적으로 동결한다.
    Object.keys(target).forEach(key => deepFreeze(target[key]));
  }
  return target;
}
profile
깃헙으로 이사중..

0개의 댓글