
[[ ... ]] )로 감싼 이름들이 내부 슬롯과 내부 메서드다.1// 모든 객체는 [[Prototype]] 이라는 내부 슬롯을 갖는다.
2// 내부 슬록은 자바스크립트 엔지의 내부 로직이므로 원칙적으로 접근할 수는 없다.
3// 하지만 [[Prototype]] 내부 슬롯의 경우. __proto__를 통해 간접적으로 접근할 수 있다.
4const o = {};
5
6o.[[Prototype]] // Uncaught SyntaxError: Unexpected token '['
7// 단, 일부 내부 슬롯과 내부 메서드에 한하여 간접적으로 접근할 수 있는 수단을 제공하기는 한다.
8o.__proto__ // Object.prototype
[[Value]] , [[Writable]] , [[Enumerable]], [[Configurable]] 이다.Object.getOwnPropertyDescriptor 메서드를 사용하여 간접적으로 확인 가능하다.1const person = {
2 name: "Lee"
3};
4
5// 프로퍼티 어트리뷰트 정보를 제공하는 프로퍼티 디스크립트 객체를 반환
6console.log(Object.getOwnPropertyDescriptor(person, 'name'));
Object.getOwnPropertyDescriptor 메서드에 객체의 참조와 프로퍼티 키를 문자열로 전달Object.getOwnPropertyDescriptor 메서드는 프로퍼티 어트리뷰트의 정보를 제공하는 프로퍼티 디스크립터 객체를 반환하다.존재하지 않는 프로퍼티나 상속 받은 프로퍼티에 대한 프로퍼티 디스크립터를 요구하면 undefined 반환
Object.getOwnPropertyDescriptor 메서드는 하나의 프로퍼티에 대한 프로퍼티 디스크립터를 반환Object.getOwnPropertuDescriptors 메서드는 입력 받은 객체의 참조의 모든 프로퍼티 디스크립터를 반환한다.1const person = {
2 name: "Lee"
3};
4
5person.age = 20;
6
7// 모든 프로퍼티의 프로퍼티 어트리뷰트 정보를 제공하는 프로퍼티 디스크립트 객체들을을 반환
8console.log(Object.getOwnPropertyDescriptors(person));
9/*
10{
11 name: {value: 'Lee', writable: true, enumerable: true, configurable: true}
12 age: {value: 20, writable: true, enumerable: true, configurable: true}
13}
14*/
[[Value]] (value)[[Writable]] (writable)[[Enumerable]] (enumerable)[[Enumerable]]의 값이 false인 경우 해당 프로퍼티는 for … in문이나 Object.keys 메서드 등으로 열거할 수 없다.[[Configurable]] (configurable)[[Configuration]]의 값이 false인 경우 해당 프로퍼티의 삭제, 프로퍼티 어트리뷰트 값의 변경이 금지된다.[[Writable]]이 true인 경우 [[Value]]의 변경과 [[Writable]]을 false로 변경하는 것은 허용된다.[[Get]] (get)[[Get]]의 값, 즉 getter 함수가 호출되고 그 결과가 프로퍼티 값으로 반환된다.[[Set]] (set)[[Set]]의 값, 즉 setter 함수가 호출되고 그 결과가 프로퍼티 값으로 저장된다.[[Enumerable]] (enumerable)[[Enumerable]]과 같다.[[Configurable]] (configurable)[[Configurable]]과 같다.1const person = {
2 firstName: "Ungmo",
3 lastName: "Lee",
4
5 // fullName은 접근자 함수로 구성된 접근자 프로퍼티다.
6 // getter 함수
7 get fullName() {
8 return `${this.firstName} ${this.lastName}`;
9 },
10
11 set fullName(name) {
12 [this.firstName, this.lastName] = name.split(' ');
13 }
14};
15
16console.log(person.firstName + " " + person.lastName); // Ungmo Lee
17
18person.fullName = "Heegun Lee";
19
20console.log(person); // {firstName: "Heegun", lastName: "Lee"}
21
22console.log(person.fullName); // Heegun Lee
23
24// firstName은 데이터 프로퍼티다
25// 데이터 프로퍼티는 [[Value]], [[Writable]], [[Enumerable]], [[Configurable]]
26// 프로퍼티 어트리뷰트를 갖는다.
27console.log(Object.getOwnPropertyDescriptor(person, "firstName"));
28// {value: "Heegun", writable: true, enumerable: true, configurable: true}
29
30// fullName 접근자 프로퍼티다
31// 접근자 프로퍼티는 [[Get]], [[Set]], [[Enumerable]], [[Configurable]]
32/// 프로퍼티 어트리뷰트를 갖는다.
33console.log(Object.getOwnPropertyDescriptor(person, "fullName"));
34// {get: f, set: f, enumerable: true, configurable: true}
fullName에 접근하면 내부적으로 [[Get]] 내부 메서드가 호출되어 다음과 같이 동작한다.프로퍼티 키가 유효한지 확인한다. 프로퍼티 키는 문자열 또는 심벌이어야 한다. 프로퍼티 키 "fullName"은 문자열 이므로 유효한 프로퍼티 키다.
프로토타입 체인에서 프로퍼티를 검색한다. person 객체에 fullName 프로퍼티가 존재한다.
검색된 fullName 프로퍼티가 데이터 프로퍼티인지 접근자 프로퍼티인지 확인한다. fullName 프로퍼티는 접근자 프로퍼티다.
[[Get]]의 값, 즉 getter 함수를 호출하여
그 결과를 반환한다. 프로퍼티 fullName의 프로퍼티 어트리뷰트 [[Get]]의 값은
Object.getOwnPropertyDescriptor 메서드가 반환하는 프로퍼티 디스크립터 객체의
get 프로퍼티 값과 같다.1// 일반 객체의 __proto__는 접근자 프로퍼티다.
2console.log(Object.getOwnPropertyDescriptor(Object.prototype, "__proto__"));
3// {get: f, set: f, enumerable: false, configurable: true}
4
5// 함수객체의 prototype은 데이터 프로퍼티다
6console.log(Object.getOwnPropertyDescriptor(function() {}, "prototype"));
7// {value: { ... }, writable: true, enumerable: false, configurable: true}
Object.defineProperty 메서드를 사용해 프로퍼티 어트리뷰트를 정의할 수 있다.1const person = {};
2
3// 데이터 프로퍼티 정의
4Object.defineProperty(person, "firstName", {
5 value: "Ungmo",
6 writable: true,
7 enumerable: true,
8 configurable: true,
9});
10
11Object.defineProperty(person, "lastName", {
12 value: "Lee",
13});
14
15let descriptor = Object.getOwnPropertyDescriptor(person, "firstName");
16console.log("firstName", descriptor);
17// firstName { value: 'Ungmo', writable: true, enumerable: true, configurable: true }
18
19// 디스크립터 객체의 프로퍼티를 누락시키면 undefined, false가 기본값이다.
20descriptor = Object.getOwnPropertyDescriptor(person, "lastName");
21console.log("lastName", descriptor);
22// lastName { value: 'Lee', writable: false, enumerable: false, configurable: false }
23
24// [[Enumerable]]의 값이 false인 경우
25// 해당 프로퍼티는 for...in 문이나 Object.keys 등으로 열거할 수 없다.
26// lastName 프로퍼티는 [[Enumerable]]의 값이 false이므로 열거되지 않는다.
27console.log(Object.keys(person)); // [ 'firstName' ]
28
29// [[Writable]]의 값이 false인 경우 해당 프로퍼티의 [[Value]]의 값을 변경할 수 없다.
30// lastName 프로퍼티는 [[Writable]]의 값이 false이므로 값을 변경할 수 없다.
31// 이때 값을 변경하면 에러는 발생하지 않고 무시된다.
32person.lastName = "Kim";
33
34// [[Configurable]]의 값이 false인 경우 해당 프로퍼티를 삭제할 수 없다.
35// lastName 프로퍼티는 [[Configurable]]의 값이 false이므로 삭제할 수 없다.
36// 이때 프로퍼티를 삭제하면 에러는 발생하지 않고 무시된다.
37delete person.lastName;
38
39// [[Configurable]]의 값이 false인 경우 해당 프로퍼티를 재정의할 수 없다.
40// Object.defineProperty(person, "lastName", { enumerable: true });
41// TypeError: Cannot redefine property: lastName
42
43descriptor = Object.getOwnPropertyDescriptor(person, "lastName");
44console.log("lastName", descriptor);
45// lastName { value: 'Lee', writable: false, enumerable: false, configurable: false }
46
47// 접근자 프로퍼티 정의
48Object.defineProperty(person, "fullName", {
49 // getter 함수
50 get() {
51 return `${this.firstName} ${this.lastName}`;
52 },
53 // setter 함수
54 set(name) {
55 [this.firstName, this.lastName] = name.split(" ");
56 },
57 enumerable: true,
58 configurable: true,
59});
60
61descriptor = Object.getOwnPropertyDescriptor(person, "fullName");
62console.log("fullName", descriptor);
63// fullName {get: ƒ, set: ƒ, enumerable: true, configurable: true}
64
65person.fullName = "Heegun Lee";
66console.log(person); // { firstName: 'Heegun', lastName: 'Lee'}Object.defineProperty 메서드로 프로퍼티를 정의할 때 프로퍼티 디스크립터 객체의 프로퍼티 일부 생략할 수 있다.Object.defineProperties 메서드를 사용하면 여러개의 프로퍼티를 한 번에 정의할 수 있다.1const person = {};
2
3Object.defineProperties(person, {
4 // 데이터 프로퍼티 정의
5 firstName: {
6 value: "Ungmo",
7 writable: true,
8 enumerable: true,
9 configurable: true,
10 },
11 lastName: {
12 value: "Lee",
13 writable: true,
14 enumerable: true,
15 configurable: true,
16 },
17 // 접근자 프로퍼티 정의
18 fullName: {
19 // getter 함수
20 get() {
21 return `${this.firstName} ${this.lastName}`;
22 },
23 // setter 함수
24 set(name) {
25 [this.firstName, this.lastName] = name.split(" ");
26 },
27 enumerable: true,
28 configurable: true,
29 },
30});
31
32person.fullName = "Heegun Lee";
33console.log(person); // {firstName: "Heegun", lastName: "Lee"}
Object.preventExtensions 메서드는 객체의 확장을 금지한다.
Object.isExtensible 메서드를 통해 확장이 가능한 객체인지 확인할 수 있다.Object.seal 메서드는 객체를 밀봉한다.
Object.isSealed 메서드를 통해 밀봉된 객체인지 확인할 수 있다.Object.freeze 메서드는 객체를 동결한다.
Object.isFrozen 메서드를 통해 동결된 객체인지 확인할 수 있다.Object.freeze 메서드로 객체를 동결하더라도 중첩 객체 까지 동결할 수 없다.1const person = {
2 name: "Lee",
3 address: { city: "Seoul" },
4};
5
6// 얕은 객체 동결
7Object.freeze(person);
8
9// 직속 프로퍼티만 동결한다.
10console.log(Object.isFrozen(person)); // true
11// 중첩 객체까지 동결하지 못한다.
12console.log(Object.isFrozen(person.address)); // false
13
14person.address.city = "Busan";
15console.log(person); // { name: 'Lee', address: { city: 'Busan' } }
Object.freeze 메서드를 호출해야 한다.1function deepFreeze(target) {
2 // 객체가 아니거나 동결된 객체는 무시하고 객체이고 동결되지 않은 객체만 동결한다.
3 if (!target || typeof target !== "object" || Object.isFrozen(target)) {
4 return target;
5 }
6
7 Object.freeze(target);
8 Object.keys(target).forEach((key) => deepFreeze(target[key]));
9
10 return target;
11}
12
13const person = {
14 name: "Lee",
15 address: { city: "Seoul" },
16};
17
18// 깊은 객체 동결
19deepFreeze(person);
20
21console.log(Object.isFrozen(person)); // true
22// 중첩 객체까지 동결한다.
23console.log(Object.isFrozen(person.address)); // true
24
25person.address.city = "Busan";
26console.log(person); // { name: 'Lee', address: { city: 'Seoul' } }