[딥 다이브 스터디] 24.03.21 프로퍼티 어트리뷰트

윤여찬's avatar
Mar 20, 2024
[딥 다이브 스터디] 24.03.21 프로퍼티 어트리뷰트

16.1 내부 슬롯과 내부 메서드

앞으로 살펴볼 프로퍼티 어트리뷰트를 이해하기 위해 먼저 내부 슬롯과 내부 메서드의 개념에 대해 알아보아야한다.
 
내부 슬롯과 내부 메서드는 자바스크립트 엔진의 구현 알고리즘을 설명하기 위해 ECMAScript 사양에서 사용하는 의사 프로퍼티의사 메서드다.
ECMAScript 사양에 등장하는 이중 대괄호 ([[...]])로 감싼 이름들이 내부 슬롯과 내부 메서드다.
내부슬롯과 내부 메서드는 ECMAScript 사양에 정의된 대로 구현되어 자바스크립트 엔진에서 실제로 동작하지만 개발자가 직접 접근할 수 있도록 외부로 공개된 프로퍼티는 아니다.
즉 내부 슬롯과 내부 메서드는 자바스크립트 엔진의 내부 로직이므로 원칙적으로 자바스크립트는 내부 슬롯과 내부 메서드에 직접적으로 접근하거나 호출할 수 있는 방법을 제공하지 않는다. 단. 일부 내부 슬롯과 내부 메서드에 한하여 간접적으로 접근할 수 있는 수단을 제공하기는 한다.
예를 들어, 모든 객체는 [[Prototype]]이라는 내부 슬롯을 갖는다. 내부 슬롯은 자바스크립트 엔진의 내부 로직이므로 원칙적으로 직접 접근할 수 없지만 [[Prototype]] 내부 슬롯의 경우, __proto__를 통해 간접적으로 접근할 수 있다.
const o = {}; // 내부 슬롯은 자바스크립트 엔진의 내부 로직이므로 직접 접근할 수 없다. o.[[Prototype]] // -> Uncaught SyntaxError: Unexpected token '[' // 단, 일부 내부 슬롯과 내부 메서드에 한하여 간접적으로 접근할 수 있는 수단을 제공한다. o.__proto__ // Object.prototype

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

자바스크립트 엔진은 프로퍼티를 생성할 때 프로퍼티의 상태를 나타내는 프로퍼티 어트리뷰트를 기본값으로 자동 정의한다.
프로퍼티의 상태란 프로퍼티의 값, 값의 갱신 가능 여부, 열거 가능 여부, 재정의 가능 여부를 말한다.
프로퍼티 어트리뷰트는 자바스크립트 엔진이 관리하는 내부 상태 값인 내부 슬롯 [[Value]], [[Writable]], [[Enumerable]], [[Configurable]]이다.
따라서 프로퍼티 어트리뷰트에 직접 접근할 수 없지만 Object.getOwnPropertyDescriptor 메서드를 사용하여 간접적으로 확인할 수는 있다.
const person = { name: 'Lee', }; // 프로퍼티 어트리뷰트 정보를 제공하는 프로퍼티 디스크립터 객체를 반환한다. console.log(Object.getOwnPropertyDescriptor(person, 'name')); // { value: "Lee", wirtable: true, enumerable: true, configurable: true }
Object.getOwnPropertyDescriptor 메서드를 호출할 때 첫 번째 매개변수에는 객체의 참조를 전달하고, 두번째 매개변수에는 프로퍼티 키를 문자열로 전달한다. 이때 Object.getOwnPropertyDescriptor 메서드는 프로퍼티 어트리뷰트 정보를 제공하는 프로퍼티 디스크립터 객체를 반환한다.
const person = { name: 'Lee', }; person.age = 20; // 프로퍼티 동작 생성 // 모든 프로퍼티의 프로퍼티 어트리뷰트 정보를 제공하는 프로퍼티 디스크립터 객체들을 반환한다 console.log(Object.getOwnPropertyDescriptor(person));

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

프로퍼티는 데이터 프로퍼티접근자 프로퍼티로 구분할 수 있다.
  • 데이터 프로퍼티
    • 키와 값으로 구성된 일반적인 프로퍼티다. 지금까지 살펴본 모든 프로퍼티는 데이터 프로퍼티이다.
  • 접근자 프로퍼티
    • 자체적으로는 값을 갖지 않고 다른 데이터 프로퍼티의 값을 읽거나 저장할 때 호출되는 접근자 함수로 구성된 프로퍼티다.

16.3.1 데이터 프로퍼티

데이터 프로퍼티는 다음과 같은 프로퍼티 어트리뷰트를 갖는다.
이 프로퍼티 어트리뷰트는 자바스크립트 엔진이 프로퍼티를 생성할 때 기본 값으로 자동 정의 된다.
notion image
const person = { name: 'Lee', }; // 프로퍼티 어트리뷰트 정보를 제공하는 프로퍼티 디스크립터 객체를 취득한다. console.log(Object.getOwnPropertyDescriptor(person, 'name')); // { value: "Lee", wirtable: true, enumerable: true, configurable: true }
Object.getOwnPropertyDescriptor 메서드가 반환한 프로퍼티 디스크립터 객체를 살펴보면 value 프로퍼티의 값은 ‘LEE’다. 이것은 프로퍼티 어트리뷰트 VALUE 값이 LEE 인것을 의미한다. 그리고 writable, enumerable, configurable의 값은 모두 true인 것을 의미한다.
이처럼 프로퍼티가 생성될 때 value의 값은 프로퍼티 값으로 초기화되며 writable, enumerable, configurable의 값은 true로 초기화 된다. 이것은 프로퍼티를 동적 추가해도 마찬가지 이다.

16.3.2 접근자 프로퍼티

값이 아닌 접근자 함수로 구성된 property로, data property의 값을 참조/저장 시 사용됨

Property attributes

  • [[Get]]: data property 값 참조 시 호출되는 접근자 함수(getter)
  • [[Set]]: data property 값 저장 시 호출되는 접근자 함수(setter)
  • [[Enumerable]][[Configurable]]
const person = { // 데이터 프로퍼티 firstName: "J", lastName: "K", // 접근자 프로퍼티 get fullName() { return `${this.firstName} ${this.lastName}`; }, set fullName(name) { [this.firstName, this.lastName] = name.split(" "); }, }; // 접근자 프로퍼티를 통한 프로퍼티 값의 저장 person.fullName = "first last"; console.log(person); // {firstName: 'first', lastName: 'last'} // 접근자 프로퍼티를 통한 프로퍼티 값의 참조 console.log(person.fullName); // first last // 데이터 프로퍼티의 property attributes console.log(Object.getOwnPropertyDescriptor(person, "firstName")); // {value: 'first', writable: true, enumerable: true, configurable: true} // 접근자 프로퍼티의 property attributes console.log(Object.getOwnPropertyDescriptor(person, "fullName")); // {enumerable: true, configurable: true, get: ƒ, set: ƒ}

16.4 프로퍼티 정의

프로퍼티 정의란?
새로운 프로퍼티를 추가하면서 프로퍼티 어트리뷰트를 명시적으로 정의하거나, 기존 프로퍼티의 프로퍼티 어트리뷰트를 재정의하는 것을 말하는데 예를 들어보면 프로퍼티 값을 갱신 가능하도록 할 것 인지, 프로퍼티를 열거 가능하도록 할 것인지, 프로퍼티를 재정의 가능하도록 할 것인지 정의할 수 있다.
이를 통해 객체의 프로퍼티가 어떻게 동작해야 하는지를 명확히 정의할 수 있다!
 
Object.defineProperty메서드를 사용하면 프로퍼티의 어트리뷰트를 정의할 수 있다. 인수로는 객체의 참조와 데이터 프로퍼티의 키인 문자열, 프로퍼티 디스크립터 객체를 전달한다.
// 데이터 프로퍼티 정의 const person = {}; Object.defineProperty(person, 'firstName', { value: 'YOUN', writable: true, enumerable: true, configurable: true, }); Object.defineProperty(person, 'lastName', { value: 'yeochan', }); let descriptor = Object.getOwnPropertyDescriptor(person, 'firstName'); // firstName { value: 'YOUN', writable: true, enumerable: true, configurable: true } console.log('firstName', descriptor); // 디스크립터 객체의 프로퍼티를 누락시키면 undefined, false가 기본 값이다. descriptor = Object.getOwnPropertyDescriptor(person, 'lastName'); /* 출력 결과를 비교해보면 확실히 알 수 있다. lastName { value: 'yeochan', writable: false, enumerable: false, configurable: false } */ console.log('lastName', descriptor); // [[Enumerable]]의 값이 false인 경우 // 해당 프로퍼티는 for...in 문이나 Object.keys 등으로 열거할 수 없다. // lastName 프로퍼티는 [[Enumerable]]의 값이 false이므로 열거되지 않는다. console.log(Object.keys(person)); // [ 'firstName' ] // [[Writble]]의 값이 false인 경우 해당 프로퍼티의 [[Value]]의 값을 변경할 수 없다. // lastName 프로퍼티는 [[Writble]]의 값이 false이므로 값을 변경할 수 없다. // 이때 값을 변경하면 에러는 발생하지 않고 무시된다. person.lastName = '윤'; // [[configurable]]의 값이 false인 경우 해당 프로퍼티를 삭제할 수 없다. // Object.defineProperty(person, 'lastName', { enumerable: true }); // TypeError: Cannot redefine property: lastName /* lastName { value: 'yeochan', writable: false, enumerable: false, configurable: false } */ descriptor = Object.getOwnPropertyDescriptor(person, 'lastName'); console.log('lastName', descriptor); // 접근자 프로퍼티 정의 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); person.fullName = 'yeochan Youn'; console.log(person);
Object.defineProperty 메서드로 프로퍼티를 정의할 때 프로퍼티 디스크립터 객체의 프로퍼티를 일부 생략할 수 있다. 프로퍼티 디스크립터 객체에서 생략된 어트리뷰트는 다음과 같이 기본값이 적용된다.
notion image
Object.defineProperty 메서드는 한번에 하나의 프로퍼티만 정의할 수 있다. Object.defineProperties 메서드를 사용하면 어러 개의 프로퍼티를 한 번에 정의할 수 있다.
const person = {}; Object.defineProperties(person, { // 데이터 프로퍼티 정의 firstName: { value: 'yeochan', writable: true, enumerable: true, configurable: true, }, lastName: { value: 'YOUN', writable: true, enumerable: true, configurable: true, }, fullName: { get() { return `${this.firstName} ${this.lastName}`; }, // setter 함수 set(name) { [this.firstName, this.lastName] = name.split(' '); }, enumerable: true, configurable: true, } }) person.fullName = 'yeochan Youn'; // { firstName: 'yeochan', lastName: 'Youn', fullName: [Getter/Setter] } console.log(person);

16.5 객체 변경 방지

notion image

16.5.1 객체 확장 금지

  • Object.preventExtensions: property 추가 금지
    • Object.isExtensible: 확장 가능한 객체인지 확인
const person = { firstName: "J", }; console.log(Object.isExtensible(person)); // true Object.preventExtensions(person); console.log(Object.isExtensible(person)); // false // property 추가 금지 but strict mode 아니면 에러 X person.lastName = "K"; console.log(person); // {firstName: 'J'}

16.5.2 객체 밀봉

  • Object.seal: property 값 읽기/쓰기만 가능
    • Object.isSealed: 밀봉된 객체인지 확인
cf) 밀봉된 객체의 configurable property attribute는 false
const person = { firstName: "J", }; console.log(Object.isSealed(person)); // false Object.seal(person); console.log(Object.isSealed(person)); // true console.log(Object.getOwnPropertyDescriptors(person)); // { // "firstName": { // "value": "J", // "writable": true, // "enumerable": true, // "configurable": false // } // } // property 값 읽기/쓰기 가능 person.firstName = "H"; console.log(person.firstName); // H // property 추가 금지 but strict mode 아니면 에러 X person.lastName = "K"; console.log(person); // {firstName: 'H'} // property 삭제 금지 but strict mode 아니면 에러 X delete person.firstName; console.log(person); // {firstName: 'H'} // property attribute 재정의 금지 Object.defineProperty(person, "firstName", { configurable: true, }); // Uncaught TypeError: Cannot redefine property: firstName

16.5.3 객체 동결

  • Object.freeze: property 값 읽기만 가능
    • Object.isFrozen: 동결된 객체인지 확인
cf) 동결된 객체의 writable/configurable property attribute는 false
const person = { name: "J", }; console.log(Object.isFrozen(person)); // false Object.freeze(person); console.log(Object.isFrozen(person)); // true console.log(Object.getOwnPropertyDescriptor(person, "name")); // {value: 'J', writable: false, enumerable: true, configurable: false} // property 값 쓰기 금지 but strict mode 아니면 에러 X person.name = "H"; console.log(person.name); // J

16.5.4 불변 객체

위의 객체 변경 방지 메소드들은 얕은 변경만 방지, 즉 직속 property만 변경이 방지된다.
const person = { name: { first: "J", last: "K", }, }; Object.freeze(person); console.log(Object.isFrozen(person.name)); // false person.name.first = "H"; console.log(person.name.first); // H
따라서 중첩 객체까지 동결된 읽기 전용의 불변 객체를 구현하려면, 객체를 값으로 갖는 모든 property에 대해 재귀적으로 Object.freeze를 호출해야 한다.
function deepFreeze(target) { if (target && typeof target === "object" && !Object.isFrozen(target)) { Object.freeze(target); Object.keys(target).forEach((key) => deepFreeze(target[key])); } return target; } const person = { name: { first: "J", last: "K", }, }; deepFreeze(person); person.name.first = "H"; console.log(person.name.first); // "J"
Share article
RSSPowered by inblog