진취적 삶
16장 property attribute 본문
16.1 내부 슬롯과 내부 메서드
내부 슬롯과 내부 메서드는 js 엔진의 내부 로직이므로 원칙적으로 js는 내부 슬롯과 내부 메서드에
직접 접근하거나 호출할수 있는 방법을 제공하지 않는다 .
const obj = {};
obj.__proto__;
__ proto __ 을 통해 간접적으로 접근할수 있다.
16.2 프로퍼티 어트리뷰트와 프로퍼티 디스크립터 객체
js 엔진은 프로퍼티를 생성할 때 프로퍼티의 상태를 나타내는 property attribute를 기본값으로
자동 정의한다.
프로퍼티의 상태란 프로퍼티의 값(value) ,값의 갱신 가능 여부(writable) ,열거 가능 여부(enumerable) ,재정의 가능 여부 (configurable)
const person = {
name: "suha",
};
person.age = 20;
console.log(Object.getOwnPropertyDescriptor(person, "name"));
// { value: 'suha', writable: true, enumerable: true, configurable: true }
console.log(Object.getOwnPropertyDescriptors(person));
// {
// name: {
// value: 'suha',
// writable: true,
// enumerable: true,
// configurable: true
// },
// age: { value: 20, writable: true, enumerable: true, configurable: true }
// }
16.3 데이터 프로퍼티와 접근자 프로퍼티
프로퍼티는 데이터 프로퍼티와 접근자 프로퍼티로 구분할수 있다 .
- 데이터 프로퍼티 : key value 로 구성된 일반적인 프로퍼티
- 접근자 프로퍼티 : 자체적으로는 값을 갖지 않고 다른 데이터 프로퍼티의 값을 읽거나 저장할때 호출 되는 접근자 함수로 구성된 프로퍼티
16.3.1 데이터 프로퍼티
| 프로퍼티 어트리뷰트 | 프로퍼티 디스크립터 객체의 프로퍼티 | 설명 | | --- | --- | --- | | [[value]] | value | * 프로퍼티 키를 통해 프로퍼티 값에 접근하면 반환되는 값
- 프로퍼티가 없으면 프로퍼티를 동적 생성하고 생성된 프로퍼티의 value에 값을 저장한다 | | [[Writeable] | writable | * 프로퍼티 값의 변경 가능 여부를 나타내며 불리언 값을 갖는다 *writable 의 값이 false 인 경우 해당 프로퍼티의 value 값을 변경할수 없는 읽기 전용 프로퍼티가 된다 | | [[Enumerable]] | enumerable | *프로퍼티의 열거 가능 여부를 나타내며 불리언 값을 갖는다 *enumerable 의 값이 false 인경우 해당 프로퍼티는 for 문이나 object.keys 메서드 등으로 열거할수 없다 . | | [[Configurable]] | configurable | *프로퍼티의 재정의 가능 여부를 나타내며 불리언 값을 갖는다
- configurable 의 값이 false 인 경우 해당 프로퍼티의 삭제 프로퍼티 어트리부트 값의 변경이 금지된다. |
16.3.2 접근자 프로퍼티
자체적으로 값을 갖지 않고 다른 데이트 프로퍼티의 값을 읽거나 저장할 때 사용하는
접근자 함수로 구성된 프로퍼티 이다 .
| 프로퍼티 어트리뷰트 | 프로퍼티 디스크립터 객체의 프로퍼티 | 설명 | | --- | --- | --- | | [[get]] | get | 접근자 프로퍼티를 통해 데이터 프로퍼티의 값을 읽을 때 호출되는 접근자 함수 접근자 프로퍼티 키로 프로퍼티 값에 접근하면 프로퍼티 어트리뷰트의 값 즉 getter 함수가 호출되고 그 결과가 프로퍼티의 값으로 호출된다. | | [[set]] | set | 접근자 프로퍼티를 통해 데이터 프로퍼티의 값으 저장할때 호출되는 접근자 함수 접근자 프로퍼티 키로 프로퍼티 값에 저장하면 프로퍼티 어트리뷰트의 값 즉 setter 함수가 호출되고 그 결과가 프로퍼티 값으로 저장 | | [[Enumerable]] | enumerable | 데이터 프로퍼티 와 같다 | | [[Configurable]] | configurable | 데이터 프로퍼티 와 같다 |
const person = {
//data property
firstName: "suha",
lastName: "hwang",
//fullName 은 접근자 프로퍼티 이다 .
//getter
get fullName() {
return `${this.firstName} ${this.lastName}`;
},
//setter
set fullName(name) {
[this.firstName, this.lastName] = name.split(" ");
},
};
//data property 를 통한 property 값 참조
console.log(person.firstName + " " + person.lastName);
//접근자 property 를 통한 property 값 저장
//접근자 fullName 에 저장하면 setter 함수가 호출
person.fullName = "suha hwang";
console.log(person);
//접근자 property 를 통한 property 값 참조
//접근자 fullName 에 저장하면 getter 함수가 호출
console.log(person.fullName);
//firstName 은 데이터 프로퍼티
let descriptor = Object.getOwnPropertyDescriptor(person, "firstName");
console.log(descriptor);
//fullName은 접근자 프로퍼티
descriptor = Object.getOwnPropertyDescriptor(person, "fullName");
console.log(descriptor);
firstName lastName 은 데이터 프로퍼티
getter/setter 함수의 이름 fullName 이 접근자 프로퍼티이다
접근자 프로퍼티는 자체적으로 값(value)을 가지지 않으며 데이터 프로퍼티의 값을 읽거나 저장할때 관여
내부 슬롯/메서드 관점
- 프로퍼티 키가 유효한지 확인 , 프로퍼티 키는 문자열 또는 symbol 이어야함 ’fullName’ 은 문자열이므로 유효
- 프로토타입 체인에서 프로퍼티를 검색 , person 객체에 fullName 프로퍼티 존재
- 검색된 fullName 이 데이터 or 접근자 프로퍼티인지 확인 ,fullName 은 접근자 프로퍼티
- fullName 의 getter 을 호출하여 결과를 반환한다 .
프로토타입 : 어떤 객체의 상위 객체의 역할을 하는 객체다 .
프로토타입은 하위 객체에게 자신의 프로퍼티와 메서드를 상속한다.
프로토타입 객체의 프로퍼티나 메서드를 상속받은 하위 객체는 자신의 프로퍼티 또는 메서드인
것처럼 자유롭게 사용할수 있다.
16.4 프로퍼티 정의
새로운 프로퍼티를 추가하면서 프로퍼티 어트리뷰트를 명시적으로 정의하거나 ,기존 프로퍼티의 프로퍼티 어트리뷰트를 재정희 하는것을 말한다.
Object.defineProperty 메서드를 사용하여 프로퍼티의 어트리뷰트를 정의할수 있다 .
const { values } = require("lodash");
const person = {};
//data property
Object.defineProperty(person, "firstName", {
value: "suha",
writable: true,
enumerable: true,
configurable: true,
});
Object.defineProperty(person, "lastName", {
value: "hwang",
});
let descriptor = Object.getOwnPropertyDescriptor(person, "firstName");
console.log("firstName ", descriptor);
console.log("--------------------------------------------");
//firstName{ value: 'suha', writable: true, enumerable: true, configurable: true }
//디스크립터 객체의 기본값을 누락시키면 false 가 기본값이다 .
descriptor = Object.getOwnPropertyDescriptor(person, "lastName");
console.log("lastName ", descriptor);
console.log("--------------------------------------------");
// enumerable false 인 경우
// 해당 프로퍼티는 for in , Object keys 등으로 열거 불가능
//lastName 은 false 이여서 열거 불가능
//[ 'firstName' ]
console.log(Object.keys(person));
console.log("--------------------------------------------");
//writable false 인 경우 value 값 변경 불가능
// 에러는 발생하지 않고 무시
person.lastName = "kim";
//configurable false 이면 프로퍼티 삭제 불가능
// lastName property 는 false 이므로 삭제 불가능
// 에러는 발생하지 않고 무시
delete person.lastName;
descriptor = Object.getOwnPropertyDescriptor(person, "lastName");
console.log(descriptor);
console.log("--------------------------------------------");
console.log(person);
//접근자 프로퍼티 정의
Object.defineProperty(person, "fullName", {
get() {
return `${this.firstName} ${this.lastName}`;
},
set(name) {
[this.firstName, this.lastName] = name.split(" ");
},
enumerable: true,
configurable: true,
});
descriptor = Object.getOwnPropertyDescriptor(person, "fullName");
console.log("fullName", descriptor);
person.fullName = "hwang suha";
console.log(person);
16.5 객체 변경 방지
객체는 변경 가능한 값 . 프로퍼티 추가 삭제 갱신 가능
Object.defineProperty 또는 Object.defineProperties 메서드를 사용하여 재정의 가능
| 구분 | 메서드 | 프로퍼티 추가 | 프로퍼티 삭제 | 프로퍼티 값 읽기 | 프로퍼티 값 쓰기 | 프로퍼티 어트리뷰트 재정의 | | --- | --- | --- | --- | --- | --- | --- | | 객체 확장 금지 | Object.preventExtensions | x | 0 | 0 | 0 | 0 | | 객체 밀봉 | Object.seal | x | x | 0 | 0 | x | | 객체 동결 | Object.freeze | x | x | 0 | x | x |
16.5.1 객체 확장 금지
Object.preventExtensions 메서드는 객체의 확장을 금지한다.
확장이 금지된 객체는 프로퍼티 추가가 금지된다.
const person = { name: "suha" };
// person 객체는 확장이 금지된 객체가 아님
console.log(Object.isExtensible(person));
//person 객체 확장 금지 만들기
Object.preventExtensions(person);
// person 객체는 확장이 금지됨
console.log(Object.isExtensible(person));
//prevent property add
//ignore add property
person.age = 20;
console.log(person);
// prevent add but delete is ok
delete person.name;
console.log(person);
//프로퍼티 정의에 의한 프로퍼티 추가도 금지한다
Object.defineProperty(person, "age", { value: 20 });
16.5.2 객체 밀봉
객체 밀봉이란 프로퍼티 추가 및 삭제와 프로퍼티 어트리뷰트 정의 금지를 의미한다.
밀봉된 객체는 읽기와 쓰기만 가능하다
const person = { name: "suha" };
//밀봉된 객체가 아니다
console.log(Object.isSealed(person));
// 객체를 밀봉해서 추가 삭제 재정의를 금지한다 .
Object.seal(person);
// person 객체는 밀봉된 객체다
console.log(Object.isSealed(person));
//밀봉된 객체는 configurable 이 금지된다.
console.log(Object.getOwnPropertyDescriptor(person));
//추가 금지
person.age = 20;
console.log(person);
// 삭제 금지
delete person.name;
console.log(person);
// 갱신 가능
person.name = "kim";
console.log(person);
//재정의 금지
Object.defineProperty(person, "name", { configurable: true });
16.5.3 객체 동결
객체 동결이랑 프로퍼티 추가 및 삭제와 프로퍼티 어트리뷰트 재정의 금지 갱신 금지를 의미
즉 동결된 객체는 읽기만 가능하다 .
const person = { name: "suha" };
//person 객체는 동결된 객체가 아니다
console.log(Object.isFrozen(person));
// person 객체를 동결하여 프로퍼티 추가 삭제 재정의 쓰기 금지
Object.freeze(person);
//person 객체는 동결
console.log(Object.isFrozen(person));
// writable ,configurable 금지
console.log(Object.getOwnPropertyDescriptors(person));
//추가 금지
person.age = 20;
console.log(person);
//갱신 금지
person.name = "kim";
console.log(person);
//삭제 금지
delete person.name;
console.log(person);
Object.defineProperty(person, "name", { configurable: true });
16.5.4 불변객체
지금까지 본 메서드는 얕은 변경 방지로 직속 프로퍼티반 변경이 방지되고
중첩은 방지가 안됨
객체의 중첩 객체까지 동결하려면 재귀적으로 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: "suha",
address: { city: "seoul" },
};
deepFreeze(person);
console.log(Object.isFrozen(person)); //true
console.log(Object.isFrozen(person.address)); //true
person.address.city = "busan";
console.log(person); // { name: 'suha', address: { city: 'seoul' } }
'개발 도서 > 자바스크립트 deepdive' 카테고리의 다른 글
24 클로저 (0) | 2023.07.12 |
---|---|
25 클래스 (0) | 2023.07.12 |
17 생성자 함수에 의한 객체 생성 (0) | 2023.07.11 |
18 함수와 일급 객체 (0) | 2023.07.11 |
19 프로토타입 (0) | 2023.07.11 |