Front-end/Javascript

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

Daniel(빡일) 2022. 11. 2. 18:25
반응형

 

Group study background

나만 그런건지는 모르겠지만, 실무를 하다보면 잊어버리는 개념들이 있다.

가끔 FE 뉴비나 novice인분들에게 질문을 받는데, 아리송 할때만큼 쪽팔릴때가 없었다.

인간은 망각의 동물이라고 교수님께서 말씀하셨지만 반복 학습의 힘을 믿는다. React 오픈카톡방에서 모집한 스터디원분들과 함께 "모던 자바스크립트 Deep Dive" 1권 톺아보기를 시작한다!

 

정보 전달용이 아닌 개인 스터디 레코딩용 포스트입니다.

 


16.1 내부 슬롯과 내부 메서드

  내부 슬롯과 내부 메서드는 ECMAScript 사양데 정의된 대로 구현되어 자바스크립트 엔진에서 실제로 동작하지만 개발자가 직접 접근할 수 있도록 외부로 공개된 객체의 프로퍼티는 아니다. 자바스크립트 엔진의 내부 로직이므로 원친적으로 자바스크립트는 내부 슬롯과 내부 메서드에 직접 접근하거나 호출할 수 있는 방법을 제공하지 않는다.


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

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

 프로퍼티의 상태란 프로퍼티의 값(value) [[value]], 값의 갱신 가능 여부(writable) [[Writable]], 열거 가능 여부(enumerable) [[Enumerable]], 재정의 가능 여부(configurable) [[Configurable]]를 말한다. 

[예제 16-01]

const person = { name: 'Daniel' }

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


person.age = 20

console.log(Object.getOwnPropertyDescriptor(person))
/*
{ 
 name: {  value : "Daniel", wrtiable: true, enumerable: true, configurable: true}
 age: {  value : 20, wrtiable: true, enumerable: true, configurable: true}
 }
*/

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

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

16.3.1 데이터 프로퍼티

[표 16-01]

 

 

16.3.2 접근자 프로퍼티

[표 16-02]

아래 예제에서 볼 수 잇는 것처럼 접근자 함수는 getter/setter 함수처럼 사용할 수 있다.

접근자 프로퍼티는 자체적으로 값([[Value]])을 가지지 않으며 다만 데이터 프로퍼티의 값을 읽거나 저장할 때 관여할 뿐이다.

[예제 16-02]

const person = {
  firstName: 'Daniel',
  lastName: 'Park',
  
  get fullName() {
    return `${this.firstName} ${this.lastName}`
  }
  set fullName(name) {
  	[this.firstName, this.lastName] = name.split(" ");
  }
}


console.log(Object.getOwnPropertyDescriptor(person, 'fullName'));
//{get:f, set:f, enumerable: true, configurable: true}

 

 접근자 프로퍼티와 데이터 프로퍼티를 구별하는 방법

[예제 16-03]

// 일반 객체의 __proto__는 접근자 프로퍼티
Object.getOwnPropertyDescriptior(Object.prototype, '__proto__')


// 함수 객체의 prototype는 데이터 프로퍼티
Object.getOwnPropertyDescriptior(function() {}, 'prototype')

16.4 프로퍼티 정의

프로퍼티 정의: 새로운 프로퍼티를 추가하면서 프로퍼티 어트리뷰트를 명시적으로 정의하거나, 기존 프로퍼틔 프로퍼티 어튜리뷰트ㅡ를 재정의하는 것 (enumerable, writable, ...)

[예제 16-04]

const person = {}

Object.defineProperty(person,  'firstName', {
  value: 'Daniel',
  writable: true,
  enumberable: true, // 열거 가능 여부, for, Object.keys()
  configurable: true // 키 삭제 가능 여부
})


// 디스크립터 객체의 프로퍼티를 누락시키면 value는 undefiend, 속성은 false가 기본값
Object.defineProperty(person,  'lastName', {
  value: 'Park',
})


Object.defineProperty(person,  'fullName', {
  get fullName() {
    return `${this.firstName} ${this.lastName}`
  },
  set fullName(name) {
  	[this.firstName, this.lastName] = name.split(" ");
  },
  enumerable: true,
  configurable: true,
})

[표 16-03]

Object.defineProperty 메서드는 한번에 하나의 프로퍼티만 정의할 수 있다. Object.defineProperties메서드를 사용하면 여러 개의 프로퍼티를 한번에 정의할 수 있다.

[예제 16-05]

const person = {}

Object.defineProperties(person,   {
firstName: {
  value: 'Daniel',
  writable: true,
  enumberable: true, // 열거 가능 여부, for, Object.keys()
  configurable: true // 키 삭제 가능 여부
},
lastName: {
  value: 'Park',
},
fullName: {
  get fullName() {
    return `${this.firstName} ${this.lastName}`
  },
  set fullName(name) {
  	[this.firstName, this.lastName] = name.split(" ");
  },
  enumerable: true,
  configurable: true,
}
})

16.5 객체 변경 방지

자바스크립트는 객체의 변경을 방지하는 다양한 메서드를 제공한다.  객체 변경 방지 메서드들은 객체의 변경을 금지하는 강도가 다르다.
[표 16-04]

16.5.1 객체 확장 금지

Object.preventExtensions 메서드는 객체의 확장을 금지한다. 객체 확장 금지란 추가 금지를 의미하는데 이렇게 되면 Object.defineProperty 메서드 또는 동적 추가를 통한 프로퍼티 추가가 금지된다. 

[예제 16-06]

const person = { name: 'Daniel' }

console.log(Object.isExtensible(person)) //true

Object.preventExtensions(person)

console.log(Object.isExtensible(person)) //false


person.age = 20
console.log(person) // { name: 'Daniel' }

delete person.name 
console.log(person) // {}

Object.defineProperty(person, 'age', {value:20})
//TypeError: cannot define property age, object is not extensible

16.5.2 객체 밀봉

Object.seal 메서드는 프로퍼티 추가 및 삭제와 프로퍼티 어트리뷰트 재정의 금지한다. 즉, 읽기와 쓰기만 가능하다.

[예제 16-07]

const person = { name: 'Daniel' }

console.log(Object.isSealed(person)) //false

Object.seal(person)

console.log(Object.isSealed(person)) //true

console.log(Object.getOwnPeropertyDescriptors(person))
/*
{
  name: { value: "Daniel", writable: true, enumerable: true, configurable: flase},
}
*/

person.age = 20
console.log(person) // { name: 'Daniel' }

delete person.name 
console.log(person) // { name: 'Daniel' }

person.name = 'King Daniel'
console.log(person) // { name: ' King Daniel' }

Object.defineProperty(person, 'name', {configurable: true})
//TypeError: cannot redefine property: name

16.5.3 객체 동결

Object.freeze 메서드는 프로퍼티 추가 및 삭제와 프로퍼티 어트리뷰트 재정의와 값 갱신 금지 한다. 즉, 읽기만 가능하다.

[예제 16-08]

const person = { name: 'Daniel' }

console.log(Object.isFrozen(person)) //false

Object.freeze(person)

console.log(Object.isFrozen(person)) //true

console.log(Object.getOwnPeropertyDescriptors(person))
/*
{
  name: { value: "Daniel", writable: false, enumerable: true, configurable: flase},
}
*/

person.age = 20
console.log(person) // { name: 'Daniel' }

delete person.name 
console.log(person) // { name: 'Daniel' }

person.name = 'King Daniel'
console.log(person) // { name: 'Daniel' }

Object.defineProperty(person, 'name', {configurable: true})
//TypeError: cannot redefine property: name

16.5.4 불변 객체

위의 방법들은 얕은 변경 방지(Shallow Only)로 직속 프로퍼티만 변경이 방지되고 중첩 객체까지는 영향을 주지 못한다. 따라서 Object.freeze 메서드로 객체를 동결하여도 중첩 객체까지 동결할 수 없는데, 값으로 갖는 모든 프로퍼티에 재귀적으로 Object.freeze 메서드를 호출하면 해결된다.

반응형