JavaScript

[16장] 프로퍼티 어트리뷰트

잼굴 2022. 3. 8. 14:35

책 읽기

 

 

 내부 슬롯, 내부 메서드 =  JS엔진에서 사용하는 의사 프로퍼티와 의사 메서드  (Doctor 아님ㅋㅋ)

 

내부슬롯과 내부 메서드는 직접적으로 접근하거나 호출할수 없음. 

[[Prototype ]] 내부슬롯의 경우 __proto__를 통해 간접적으로 접근가능.

 

 

 

JS엔진은 프로퍼티를 생성할때 프로퍼티 상태를 나타내는 프로퍼티 어트리뷰트를 기본값으로 자동정의함.

 

 

프로퍼티상태란

 

  • 프로퍼티 값
  • 값의 갱신 가능 여부
  • 열거 가능 여부
  • 재정의 가능 여부

 

 

Object.getOwnPropertyDescriptor 메서드를 사용해 간접적으로 확인가능

 

 

console.log(Object.getOwnPropertyDescriptor());  

 

-> 프로퍼티 디스크립터 객체들을 반환한다.

 

 

프로퍼티의 종류

  1. 데이터 프로퍼티
  2. 접근자 프로퍼티

 

데이터 프로퍼티

[[Value]]  :  프로퍼티 키를 통해 프로퍼티 값에 접근하면 반환되는 값.

[[Writable]]  :  프로퍼티 값의 변경가능 여부를 나타내며 불리언 값을 갖는다.

[[Enumerable]]  :  프로퍼티의 열거 가능여부를 나타내며 불리언 값을 갖는다.

[[Configurable]]  :  프로퍼티의 재정의 가능 여부를 나타내며 불리언 값을 갖는다.

 

 

 

접근자 프로퍼티

 

[[Get]]  :  접근자 프로퍼티를 통해 데이터 프로퍼티의 값을 읽을때 호출되는 접근자 함수.

[[Set]]  :  접근자 프로퍼티를 통해 데이터 프로퍼티의 값을 저장할 때 호출되는 접근자 함수.

[[Enumerable]]  :  프로퍼티의 열거 가능여부를 나타내며 불리언 값을 갖는다.

[[Configurable]]  :  프로퍼티의 재정의 가능 여부를 나타내며 불리언 값을 갖는다.

 

const person = {
  // 데이터 프로퍼티
  firstName: 'Ungmo',
  lastName: 'Lee',
  
  // fullName은 접근자 함수로 구성된 접근자 프로퍼티이다.
  // getter 함수
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  },
  // setter 함수
  set fullName(name) {
    // 배열 디스트럭처링 할당
    [this.firstName, this.lastName] = name.split(' ');
  }
};

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

// 접근자 프로퍼티를 통한 프로퍼티 값의 저장
// 접근자 프로퍼티 fullName에 값을 저장하면 setter 함수가 호출된다.
person.fullName = 'Heegun Lee';
console.log(person); // {firstName: "Heegun", lastName: "Lee"}

// 접근자 프로퍼티를 통한 프로퍼티 값의 참조
// 접근자 프로퍼티 fullName에 접근하면 getter 함수가 호출된다.
console.log(person.fullName); // Heegun Lee

// firstName은 데이터 프로퍼티이다.
// 데이터 프로퍼티는 [[Value]], [[Writable]], [[Enumerable]], [[Configurable]] 프로퍼티 어트리뷰트를 갖는다
let descriptor = Object.getOwnPropertyDescriptor(person, 'firstName');
console.log(descriptor);
// {value: "Heegun", Writable: true, enumerable: true, configurable: true}

// fullName은 접근자 프로퍼티다.
// 접근자 프로퍼티는 [[Get]], [[Set]], [[Enumerable]], [[Configurable]] 프로퍼티 어트리뷰트를 갖는다
descriptor = Object.getOwnPropertyDescriptor(person, 'fullName');
console.log(descriptor);
// {get: f, set: f, enumerable: true, configurable: true}

 

접근자 프로퍼티 fullName으로 프로퍼티값에 접근하면 [[Get]] 내부메서드가 호출되며 작동하는 방식

 

1. 프로퍼티 키가 유효한지 확인

2. 프로타티입 체인에서 프로퍼티를 검색. person객체에 fullName 프로퍼티가 존재

3. 검색된 fullName 프로퍼티가 데이터 프로퍼티인지 접근자 프로퍼티인지 확인

4. 접근자 프로퍼티 어트리뷰트 [[Get]]의값을 호출하여 반환함.

 

 

프로퍼티 정의

프로퍼티어트리뷰트를 명시적으로 정의하거나, 기존 프로퍼티의 프로퍼티 어트리뷰트를 재정의 하는것.

const person = {};

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

Object.defineProperty(person, 'lastName', {
  value: 'Lee'
});

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

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

// [[Enumerable]]의 값이 false인 경우 해당 프로퍼티는 열거할 수 없다.
// lastName 프로퍼티는 [[Enumerable]]의 값이 false이므로 열거 불가.
console.log(Object.keys(person)); // ["firstName"]


// lastName 프로퍼티의 [[Writable]]의 값이 false이므로 값을 변경할 수 없다.
// 이때 값을 변경하면 에러는 발생하지 않고 무시된다.
person.lastName = 'Kim';

// lastName 프로퍼티의 [[Configurable]]의 값이 false이므로 삭제할 수 없다.
// 이때 프로퍼티를 삭제하면 에러는 발생하지 않고 무시된다.
delete person.lastName;

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

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

// 접근자 프로퍼티 정의
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 {get: f, set: f, enumerable: true, configurable: true}

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

 

 

프로퍼티 정의할때 일부 생략가능, 그럼 기본값이 적용됨 

Object.defineProperties 를 통해서 여러개를 한번에 정의가능

 

객체 변경 방지

  • 객체 확장 금지  :  Object.preventExtensions
  • 객체 밀봉  :        Object.seal
  • 객체 동결  :        Object.freeze

 

객체 확장 금지 : 프로퍼티 추가X                         //  삭제,읽기,쓰기, 재정의 OK

객체 밀봉  :  프로퍼티 추가, 삭제, 재정의 X          //   읽기, 쓰기  OK

객체 동결  :  프로퍼티 추가, 삭제, 쓰기, 재정의 X  // 읽기 OK

 

'JavaScript' 카테고리의 다른 글

Arrow function  (0) 2022.05.17
this함수  (0) 2022.05.17
[15장] let,const, 블록 레벨 스코프  (0) 2022.02.25
[13장, 14장] 스코프 , 전역변수의 문제점  (0) 2022.02.25
[12장] 함수  (2) 2022.02.24