
#데이터프로퍼티 #접근자프로퍼티 #프로퍼티어티리뷰트 #프로퍼티디스크립터 #객체확장방지 #객체동결 #객체밀봉 #불변객체
내부 슬롯과 내부 메서드
내부슬롯과 내부메서드는 ECMA Script 사양에서 사용하는 의사 프로퍼티와 의사 메서드이다.
모든 객체는 [[Prototype]] 이라는 내부 슬롯을 갖는다.
[[Prototype]]은 생성자 함수의 prototype 프로퍼티이다.
[[Prototype]] 내부 슬롯은 예외적으로 __proto__를 통해 간접적으로 접근할 수 있다.
- 원칙적으로 외부에서 내부 슬롯과 내부 메서드에 접근할 수 없다.
- 일부 내부슬롯과 내부메서드에 한해 간접적으로 접근할 수 있는 수단이 제공된다.
const o = {};
// 직접접근 불가
o.[[Prototype]] // Uncaught SyntaxError: Unexpected token '['
// __proto__ 를 통해 간접접근
o.__proto__
// {constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, hasOwnProperty: ƒ, __lookupGetter__: ƒ, …}
프로퍼티 어트리뷰트와 프로퍼티 디스크립터 객체
자바스크립트 엔진은 객체의 프로퍼티를 생성할때 프로퍼티의 상태를 나타내는 프로퍼티 어트리뷰트를 기본값으로 자동 정의한다.
프로퍼티의 상태란 값, 갱신가능여부, 열거가능여부, 재정의 가능여부를 말한다.
프로퍼티의 상태를 나타내는 프로퍼티 어트리뷰트는 프로퍼티의 상태값을 가진 내부 슬롯 [[Value]] , [[Writable]], [[Enumarable]]
, [[Configurable]] 을 가진다.
Object.getOwnPropertyDescription 메서드를 통해 객체의 프로퍼티 내부 슬롯을 간접적으로 확인할 수 있다.
Object.getOwnPropertyDescription(Object, propertyName)는 객체의 프로퍼티 어트리뷰트 정보를 제공하는 프로퍼티 디스크립터 객체를 반환한다.
Object.getOwnPropertyDescriptions(Object)는 객체의 모든 프로퍼티 어트리뷰트 정보를 제공하는 프로퍼티 디스크립터 객체를 반환한다.
const person = {
name: "Lee",
};
// {value: 'Lee', writable: true, enumerable: true, configurable: true}
Object.getOwnPropertyDescriptor(person, "name");
person.age = 22;
Object.getOwnPropertyDescriptors(person);
// age: {value: 22, writable: true, enumerable: true, configurable: true}
//name: {value: 'Lee', writable: true, enumerable: true, configurable: true}
데이터 프로퍼티와 접근자 프로퍼티
데이터 프로퍼티
키와 값으로 구성된 일반적인 프로퍼티.
데이터 프로퍼티는 다음과 같은 프로퍼티 어트리뷰트를 갖는다.
[[Value]] : 프로퍼티 키를 통해 접근하면 반환되는 값
[[Writable]] : 프로퍼티 값의 변경가능여부를 나타낸다
[[Enumarable]] : 프로퍼티 값의 열거가능여부를 나타내며 false인 경우 'for..in', 'Objects.keys' 메서드등으로 열거할 수 없다
[[Configurable]] : 프로퍼티의 재정의가능여부를 나타내며 false인 경우 프로퍼티의 삭제와 프로퍼티 어트리뷰트 값의 변경이 금지된다.
const person = {
name: "Lee",
};
// 프로퍼티 디스크립터 객체
//{value : "Lee", writable : true, enumarable : true, configurable : true}
Object.getOwnPropertyDescriptor(person, "name");
value는 프로퍼티 값으로 초기화 되고 나머지는 모두 true로 초기화 된다.
접근자 프로퍼티
자체적으로는 값을 가지고 있지않고 다른 데이터의 값을 읽거나 저장할 때 호출하는 접근자함수로 구성된 프로퍼티이다.
접근자 프로퍼티는 다음과 같은 프로퍼티 어트리뷰트를 가진다.
[[Get]]
접근자 프로퍼티를 통해 데이터 프로퍼티의 값을 읽을때 호출되는 접근자 함수이다.
접근자 프로퍼티 키로 프로퍼티 값에 접근하면 프로퍼티 어트리뷰트 [[Get]]의 값인 getter 함수가 호출되고
그 결과가 프로퍼티 값으로 반환된다.
[[Set]]
접근자 프로퍼티를 통해 데이터 프로퍼티의 값을 저장할때 호출되는 접근자 함수이다.
접근자 프로퍼티 키로 프로퍼티 값을 저장하면 프로퍼티 어트리뷰트 [[Set]]의 값인 setter 함수가 호출되고 그 결과가 프로퍼티 값으로 저장된다.
[[Enumarable]]
프로퍼티 값의 열거 가능 여부를 나타내며 false인 경우 'for..in', 'Objects.keys' 메서드등으로 열거할 수 없다
[[Configurable]]
프로퍼티의 재정의 가능 여부를 나타내며 false인 경우 프로퍼티의 삭제와 프로퍼티 어트리뷰트 값의 변경이 금지된다
const person = {
firstName: "Ungmo",
lastName: "lee",
//fullName 은 접근자 함수로 구성된 접근자 프로퍼티
//[[Set]]
set fullName (name){
[this.firstName, this.lastName] = name.split(" ");
}
//[[Get]]
get fullName(){
return `${this.firstName}${this.lastName}`
}
};
person.firstName + ' ' + person.lastName // "lee Ungmo"
//접근자 프로퍼티 fullName의 setter 함수가 호출된다
person.fullName = 'HeeGun Lee'
//접근자 프로퍼티 fullName의 getter 함수가 호출된다
person.fullName // HeeGun Lee
//firstName 은 person 객체의 데이터 프로퍼티이다.
let descriptor = Object.getOwnPropertyDescriptor(person, 'firstName');
descriptor // {value : HeeGun, writable : true, enumarable : true, configurable : true}
//fullName은 person 객체의 접근자 프로퍼티이다.
descriptor = Object.getOwnPropertyDescriptor(person, 'fullName');
descriptor // { get : f, set : f, enumarable : true, configurable : true}
접근자 프로퍼티로 프로퍼티 값에 접근하면 내부적으로 다음과 같이 동작한다
- 프로퍼티 키가 유효한지 확인한다.
- 프로토타입 체인에서 프로퍼티 키를 검색한다. fullName은 person 객체 안에 존재한다.
- 데이터 프로퍼티인지 접근자 프로퍼티인지 확인한다.
- 접근자 프로퍼티라면 [[Getter]] 어트리뷰트에 할당된 함수를 호출하여 함수의 결과를 반환한다.
프로퍼티 정의
프로퍼티 정의란 새로운 프로퍼티를 추가하면서 프로퍼티 어트리뷰트를 명시적으로 정의하거나,
기존 프로퍼티의 프로퍼티 어트리뷰트를 재정의하는 것을 말한다.
Object.defineProperty 메서드를 사용한다.
const person = {};
Object.defineProperty(person, "firstName", {
value: "Ungmo",
writable: true,
enumarable: true,
configurable: true,
});
Object.defineProperty(person, "lastName", {
value: "Lee",
});
let descriptor = Object.getOwnPropertyDescriptor(person, "firstName");
descriptor; // {value : Ungmo, writable : true, enumarable : true, configurable : true}
descriptor = Object.getOwnPropertyDescriptor(person, "lastName");
descriptor; // {value : Lee, writable : false, enumarable : false, configurable : false}
// [[Enumarable]]의 값이 false 인 경우 for...in Object.keys 등으로 열거할 수 없다.
Object.keys(person); // ['fistName']
//[[Writable]]이 false 인 경우 value의 값을 변경할 수 없다.
// 오류는 발생하지않고 무시된다.
person.lastName = "Kim";
person.lastName; // Lee
//[[Configurable]]이 false 인 경우 프로퍼티를 삭제할 수 없다.
delete person.lastName;
//[[Configurable]]이 false 인 경우 해당 프로퍼티를 재정의 할 수 없다.
// uncatch TypeError : cannot redefine property : lastName
Object.defineProperty(person, "lastName", { enumarable: true });
Object.defineProperty(person, "fullName", {
get() {
return `${this.firstName}${this.lastName}`;
},
set() {
[this.firstName, this.lastName] = name.split(" ");
},
enumarable: true,
configurable: true,
});
descriptor = Object.getOwnPropertyDescriptor(person, "fullName");
//{set : f, get :f, enumarable : true, configurable : true}
person.fullName = "HeeGun Lee";
person; // {firstName : 'HeaGun', lastName : 'Lee'}
Object.defineProperties() 를 사용하면 여러개의 프로퍼티를 한 번에 정의할 수 있다.
객체 변경방지
객체는 변경가능한 값이므로 재할당 없이 직접변경가능하다.
프로퍼티를 추가하거나 삭제할 수 있고 프로퍼티 값을 갱신하거나 어트리뷰트를 재정의 할 수 있다.
자바스크립트는 객체의 변경을 방지하는 다양한 메서드를 제공한다.
객체 확장 금지
객체 확장 금지란 프로퍼티 추가 금지를 의미한다.
- 추가 : X
- 삭제 : O
- 읽기 : O
- 쓰기 : O
- 재정의 : O
프로퍼티의 추가 방법에는 프로퍼티의 동적 추가와 Object.defineProperty 두 가지 방법 모두 금지된다.
Object.preventExtensions 메서드를 이용한다.
const person = { name: "Lee" };
Object.isExtensible(person); // true
Object.preventExtensions(person);
Object.isExtensible(person); // false
person.age = 20; // 무시
person; // {name : "Lee"}
delete person.name; // 확장금지상태에서 삭제는 가능하다.
person; // {}
// TypeError : Cannot define property age, object is not extensible
Object.defineProperty(person, "age", { value: 20 });
객체 밀봉
객체 밀봉이란 프로퍼티 추가 및 삭제, 프로퍼티 어트리뷰트 재정의를 금지한다.
즉 읽기와 쓰기만 가능하다
- 추가 : X
- 삭제 : X
- 읽기 : O
- 쓰기 : O
- 재정의 :X
Object.seal 메서드를 이용한다.
const person = { name: "Lee" };
Object.isSealed(person); //false
Object.seal(person);
Object.isSealed(person); //true
Object.getOwnPropertyDescriptors(person); // {value : Lee , writable : true, enumerable : true, configurable : false}
//프로퍼티 추가가 금지된다.
person.age = 20; // 무시
//프로퍼티 삭제가 금지된다.
delete person.age; // 무시
//프로퍼티 갱신은 가능하다.
person.name = "kim";
person.name; // kim
//프로퍼티 어트리뷰터 재정의가 금지된다.
//TypeError: cannot redefined property : name
Object.defineProperty(person, "name", { configurable: true });
객체 동결
객체 동결이란 프로퍼티 추가, 삭제, 어트리뷰터 재정의, 프로퍼티 값 갱신 금지를 말한다.
즉 읽기만 가능하다.
- 추가 : X
- 삭제 : O
- 읽기 : O
- 쓰기 : O
- 재정의 : O
Object.freeze 메서드를 이용한다.
const person = { name: "Lee" };
Object.isFrozen(person); //false
Object.freeze();
Object.isFrozen(person); //true
Object.getOwnPropertyDescriptors(person); // {value : Lee , writable : false, enumerable : true, configurable : false}
//프로퍼티 추가가 금지된다.
person.age = 20; // 무시
//프로퍼티 삭제가 금지된다.
delete person.age; // 무시
//프로퍼티 갱신이 금지된다.
person.name = "kim";
person.name; // Lee
//프로퍼티 어트리뷰터 재정의가 금지된다.
//TypeError: cannot redefined property : name
Object.defineProperty(person, "name", { configurable: true });
불변 객체
메서드를 활용한 변경방지는 직속 프로퍼티에만 적용가능하고 중첩 객체에는 영향을 주지 못한다.
객체의 중첩객체까지 변경방지 하기 위해서는 객체를 값으로 가지는 모든 프로퍼티에 재귀적으로 변경방지를 실행해야한다.
const person = {
name: "Lee",
address: { city: "seoul" },
};
Object.freeze(person);
Object.isFrozen(person); // true
Object.isFrozen(person.address); // false
person.address.city = "Busan";
person; //{name : 'Lee', address:{city : 'Busan'}}
person = {
name: "Lee",
address: { city: "seoul" },
};
function deepFreeze(target) {
if (target && typeof target === "object" && !Object.isFrozen(target)) {
Object.freeze(target);
Object.keys(target).forEach((key) => deepFreeze(target[key]));
}
return target;
}
deepFreeze(person);
Object.isFrozen(person); // true
Object.isFrozen(person.address); // true
person.address.city = "Busan";
person; //{name : 'Lee', address:{city : 'seoul'}}
#데이터프로퍼티 #접근자프로퍼티 #프로퍼티어티리뷰트 #프로퍼티디스크립터 #객체확장방지 #객체동결 #객체밀봉 #불변객체
'프로그래밍 > 자바스크립트 ES6' 카테고리의 다른 글
| 자바스크립트 ES6 #18 함수와 일급객체 (0) | 2023.09.19 |
|---|---|
| 자바스크립트 ES6 #17 생성자 함수 (0) | 2023.09.19 |
| 자바스크립트 ES6 #15 변수선언키워드 & 블록레벨스코프 (0) | 2023.09.18 |
| 자바스크립트 ES6 #14 전역 변수의 문제점 (0) | 2023.09.18 |
| 자바스크립트 ES6 #13 스코프 (0) | 2023.09.16 |