일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- useContext
- 드래그앤드롭
- 타입스크립트
- 프로그래머스
- useRef
- 자바스크립트
- 훅
- React
- 알고리즘 #프로그래머스 #코딩테스트 #자바스크립트
- 리액트
- javascript
- 다이나믹프로그래밍
- 백준
- 덕타이핑
- react-beautiful-dnd
- 리코일
- 완전탐색
- 알고리즘 #코딩테스트 #프로그래머스 #자바
- 백준 #알고리즘 #자바스크립트
- recoil
- 스티커
- usedebugvalue
- useLayoutEffect
- 알고리즘
- 위상정렬
- Suspense
- 프로그래머스 #알고리즘 #자바스크립트
- Today
- Total
몽환화
[자바스크립트] 프로퍼티 어트리뷰트 (Property Attribute) 본문
먼저 내부 슬롯 interneal slot과 내부 메서드 internal method란?
자바스크립트 엔진의 구현 알고리즘을 설명하기 위해 ECMAScript 사양에서 사용하는 의사 프로퍼티와 의사 메서드.
ECMAScript 사양에 등장하는 이중 대괄호 ([[...]]) 로 감싼 이름들이 내부 슬롯과 내부 메서드
개발자가 직접 접근할 수 있도록 외부로 공개된 객체의 프로퍼티는 아님
내부 슬롯과 내부 메서드는 자바스크립트 엔진의 내부 로직으로 원칙적으로 접근이나 호출 불가
그러나 일부 내부 슬롯과 내부 메서드에 한해 간접적으로 접근할 수 있는 수단 제공
자바스크립트 엔진은 프로퍼티를 생성할 때 프로퍼티의 상태를 나타내는 프로퍼티 어트리뷰트를 기본값으로 자동 정의함
프로퍼티의 상태 : 값, 값의 갱신 여부, 열거 가능 여부, 재정의 가능 여부
프로퍼티 어트리뷰트는 자바스크립트 엔진이 관리하는 내부 상태 값인 내부 슬롯이다.
따라서 직접 접근할 수는 없지만 Object.getOwnPropertyDescriptor 메서드를 사용해 간접적 확인 가능
프로퍼티 => 데이터 프로퍼티, 접근자 프로퍼티
데이터 프로퍼티
: 키와 값으로 구성된 일반적인 프로퍼티.
데이터 프로퍼티가 갖는 프로퍼티 어트리뷰트 : 자바스크립트 엔진이 프로퍼티를 생성할 때 기본값으로 자동 정의됨
프로퍼티 어트리뷰트 | 프로퍼티 디스크립터 객체의 프로퍼티 | 설명 |
[[Value]] | value | 프로퍼티 키를 통해 프로퍼티 값에 접근하면 반환되는 값 |
[[Writable]] | writable | 프로퍼티 값의 변경 가능 여부를 나타내며 불리언 값 |
[[Enumerable]] | enumerable | 프로퍼티의 열거 가능 여부를 나타내며 불리언 값 |
[[Configurable]] | configurable | 프로퍼티의 재정의 가능 여부를 나타내며 불리언 |
const person = {
name : "Lee"
};
console.log(Object.getOwnPropertyDescriptor(person, "name"));
// {value : "Lee", writable : true, enumerable : true, configurable : true}
프로퍼티가 생성될 때 [[Value]]의 값은 프로퍼티 값으로 초기화되며 나머지는 true로 초기화.
접근자 프로퍼티
: 자체적으로는 값을 갖지 않고 다른 데이터 프로퍼티의 갑을 읽거나 저장할 때 호출되는 접근자 함수로 구성된 프로퍼티
접근자 프로퍼티가 갖는 프로퍼티 어트리뷰트
프로퍼티 어트리뷰트 | 프로퍼티 디스크립터 객체의 프로퍼티 | 설명 |
[[Get]] | get | 접근자 프로퍼티를 통해 데이터 프로퍼티의 값을 읽을 때 호출되는 접근자 함수 |
[[Set]] | set | 접근자 프로퍼티를 통해 데이터 프로퍼티의 값을 저장할 때 호출되는 접근자 함수 |
[[Enumerable]] | enumerable | 프로퍼티의 열거 가능 여부를 나타내며 불리언 값 |
[[Configurable]] | configurable | 프로퍼티의 재정의 가능 여부를 나타내며 불리언 |
접근자 함수는 getter/setter라고도 부른다! 접근자 프로퍼티는 getter와 setter 함수를 모두 정의할 수도 있고 하나만 정의할 수도 있다.
const person = {
// 데이터 프로퍼티
firstName: "Hyeii",
lastName: "Yoon",
// fullName : 접근자 함수로 구성된 접근자 프로퍼티
// getter
get fullName() {
return `${this.firstName} ${this.lastName}`;
},
// setter
set fullName(name) {
[this.firstName, this.lastName] = name.split(" ");
},
};
// 데이터 프로퍼티를 통한 프로퍼티 값의 참조
console.log(person.firstName + " " + person.lastName); // Hyeii Yoon
// 접근자 프로퍼티를 통한 프로퍼티 값의 저장
// 접근자 프로퍼티 fullName에 값을 저장하면 setter 함수가 호출됨!
person.fullName = "MingMing Lee"; //
console.log(person); //{ firstName: 'MingMing', lastName: 'Lee', fullName: [Getter/Setter] }
// 접근자 프로퍼티를 통한 프로퍼티 값의 참조
// 접근자 프로퍼티 fullName에 접근하면 getter함수가 호출
console.log(person.fullName); // MingMing Lee
// firstName은 데이터 프로퍼티 !
let descriptor = Object.getOwnPropertyDescriptor(person, "firstName");
console.log(descriptor);
// {
// value: 'MingMing',
// writable: true,
// enumerable: true,
// configurable: true
// }
// fullName은 접근자 프로퍼티 !
descriptor = Object.getOwnPropertyDescriptor(person, "fullName");
console.log(descriptor);
// {
// get: [Function: get fullName],
// set: [Function: set fullName],
// enumerable: true,
// configurable: true
// }
Object.defineProperty : 한번에 하나의 프로퍼티만 정의 가능
Object.defineProperties : 여러개의 프로퍼티 한번에 저장 가능
객체 변경 방지
객체는 변경 가능한 값이므로 재할당 없이 직접 변경할 수 있다.
즉 프로퍼티를 추가하거나 삭제할 수 있고 프로퍼티 값을 갱신할 수 있으며, 메서드를 사용해 프로퍼티 어트리뷰트를 재정의할 수도 있다.
프로퍼티 정의
새로운 프로퍼티를 추라하면서 프로퍼티 어트리뷰트를 명시적으로 정의하거나, 기존 프로퍼티의 프로퍼티 어트리뷰트를 재정의하는 것.
Object.defineProperty 사용해 프로퍼티 어트리뷰트 정의 가능
Object.isExtensible 메서드를 사용해 확장이 가능한 객체인지 확인 가능
const person = {};
Object.defineProperty(person, "firstName", {
value: "Hyeii",
writable: true,
enumerable: true,
configurable: true,
});
Object.defineProperty(person, "lastName", {
value: "Yoon",
});
let descriptor = Object.getOwnPropertyDescriptor(person, "firstName");
console.log("firstName", descriptor);
// firstName {
// value: 'Hyeii',
// writable: true,
// enumerable: true,
// configurable: true
// }
// 위에서 lastName에는 일부 프로퍼티를 누락시켰다. 따라서 undefined, false가 기본값이 된다.
descriptor = Object.getOwnPropertyDescriptor(person, "lastName");
console.log("lastName", descriptor);
// lastName {
// value: 'Yoon',
// writable: false,
// enumerable: false,
// configurable: false
// }
// [[Enumerable]]이 false인 경우
// 해당 프로퍼티는 for...in 문이나 Object.keys 등으로 열거할 수 없다.
// lastName 프로퍼티는 [[Enumerable]]의 값이 false이므로 열거되지 앟는다.
console.log(Object.keys(person)); // [ 'firstName' ]
// [[writable]]이 false인 경우 해당 프로퍼티의 [[Value]]값을 변경할 수 없다
// lastName 프로퍼티는 [[writable]]의 값이 false이므로 값을 변경할 수 없다.
// 이때 에러는 발생하지 않고 무시된다
person.lastName = "Kim";
// [[configurable]]이 false인 경우 해당 프로퍼티를 재정의할 수 없다.
// Object.defineProperty(person, "lastName", { enumerable: true });
// TypeError: Cannot redefine property: lastName
// lastName의 [[Value]]는 변경되지 않는다.
descriptor = Object.getOwnPropertyDescriptor(person, "lastName");
console.log("lastName", descriptor);
// lastName {
// value: 'Yoon',
// writable: false,
// enumerable: false,
// configurable: false
// }
// 접근자 프로퍼티 정의
Object.defineProperty(person, "fullName", {
get() {
return `${this.firstName} ${this.lastName}`;
},
set(name) {
[this.firstName, this.lastName] = name.split(" ");
},
enumerable: true,
configurable: true,
});
const person = { name: "Lee" };
// person은 확장이 가능하다
console.log(Object.isExtensible(person)); // true
// 그럼 확장을 금지해보자. 프로퍼티 추가 금지!
Object.preventExtensions(person);
// 이제 확장이 금지되었다.
console.log(Object.isExtensible(person)); // false
// 이 상태에서 추가해보면 무시된다
person.age = 20;
console.log(person); // { name : 'Lee' }
// 추가는 안되지만 삭제는 가능함!
delete person.name;
console.log(person); // {}
// 프로퍼티 정의에 의해서 추가하는 것도 당연히 금지
Object.defineProperty(person, "age", { value: 20 });
// TypeError: Cannot define property age, object is not extensible
객체 밀봉
Object.seal : 객체를 밀봉한다. 프로퍼티 추가 및 삭제와 프로퍼티 어트리뷰트 재정의 금지. 밀봉된 객체는 읽기와 쓰기만 가능하다.
Object.isSealed로 확인 가능
객체 동결
Object.freeze : 객체를 동결한다. 프로퍼티 추가 및 삭제와 프로퍼티 어트리뷰트 재정의 그밎, 프로퍼티 값 갱신 금지를 의미한다. 즉 동결된 객체는 읽기만 가능하다
Object.isFrozen으로 확인 가능
불변 객체
지금까지 살펴본 변경 방지 메서드들은 얕은 변경 방지로, 직속 프로퍼티만 변경이 방지되며 중첩 객체까지는 영향을 주지 못한다. Object.freeze 메서드로 객체를 동결하여도 중첩 객체까지 동결할 수는 없다
출처 :: 모던 자바스크립트 Deep Dive
'Front > JavaScript' 카테고리의 다른 글
타입스크립트 기본 : TypeScript (0) | 2024.05.04 |
---|---|
자바스크립트 기본 (0) | 2023.12.12 |