데이터 프로퍼티와 접근자 프로퍼티
프로퍼티는 데이터 프로퍼티와 접근자 프로퍼티로 구분할 수 있다.
- 데이터 프로퍼티 : 키와 값으로 구성된 일반적인 프로퍼티다
- 접근자 프로퍼티 : 자체적으로는 값을 갖지 않고 다른 데이터 프로퍼티의 값을 읽거나 저장할 때 호출되는 접근자 함수로 구성된 프로퍼티다
데이터 프로퍼티
데이터 프로퍼티는 다음과 같은 프로퍼티 어트리뷰트를 갖는다. 프로퍼타 어트리뷰트는 자바스크립트 엔진이 프로퍼티를 생성할 때 기본값으로 자동 생성된다.
const person = {
name : 'Lee'
};
// 프로퍼티 어트리뷰트 정보를 제공하는 프로퍼티 디스크럽터 객체를 취득한다.
console.log(Object.getOwnPropertyDescriptor(person, 'name'));
// { value : "Lee", writable : true, enumerable : true, configurable : ture }
Object.getOwnPropertyDescriptor 메서드가 반환한 프로퍼티 디스트립터 객체를 살펴보면 value 프로퍼티의 값은 'Lee'이다.
이것은 프로퍼티 어트리뷰트 [[Value]]의 값이 'Lee'인 것을 의미한다. 그리고 writable, enumerble, configurable 프로퍼티의 값은 모두 true 이다.
접근자 프로퍼티
접근자 함수는 getter/setter 함수라고도 부른다.
const person = {
// 데이터 프로퍼티
firstHName : 'Ungmo',
lastName : 'Lee',
//fullName은 접근자 함수로 구성된 접근자 프로퍼티다.
// getter 함수
get fullName() {
return `${this.firstName} ${this.lastName}`;
},
set fullName(name) {
[this.firstName, this.lastName] = name.split(' ');
}
};
console.log(person.firstName + ' ' + person.lastName); // Ungmo Lee
person.fullName = 'Hee Lee';
console.log(person); // {firstName: "Hee", lastName: "Lee"}
프로퍼티 정의
프로퍼티 정의란 Object.defineProperty 메서드를 사용하여 프로퍼티의 어트리뷰트를 정의하는 것이다.
const person = {};
// 데이터 프로퍼티 정의
Object.defineProperty(person, 'firstName', {
value : 'Ungmo',
writable : true,
enumerable : true,
configurable : true
});
Object.defineProperty(perosn, 'lastName', {
value : 'Lee'
});
let descriptor = Object.getOwnPropertyDescriptor(pserson, 'firstName');
console.log('firstName', descriptor);
// firstName {value: 'Ungmo', writable: true, enumerable: true, configurable: true}
// 디스트립터 프로퍼티를 누락시키면 undefined, false가 기본값이다.
descriptor = Object.getOwnPropertyDescriptor(person, 'lastName');
console.log('lastName', descriptor);
// lastName {value : 'Lee', 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인 경우 해당 프로퍼티를 삭제할 수 없다.
// lastName 프로퍼티는 [[Configurable]]의 값이 false이므로 삭제할 수 없다.
// 이때 프로퍼티를 삭제하면 에러는 발생하지 않고 무시된다.
delete person.lastName;
객체 변경 방지
객체는 변경 가능한 값이므로 재할당 없이 직접 변경할 수 있다. 즉, 프로퍼티를 추가하거나 삭제할 수 있고, 프로퍼티의 값을 갱신할 수 있으며, Object.defineProperty 또는 Object.defineProperties 메서드를 사용하여 프로퍼티 어트리뷰트를 재정의할 수도 있다.
객체 확장 금지
Object.preventExtensions 메서드는 객체의 확장을 금지한다. 객체 확장 금지란 프로퍼티 추가 금지를 의미한다.
즉, 확장이 금지된 객체는 프로퍼티 추가가 금지된다. 확장이 가능한 객체인지 여부는 Object.isExtensible 메서드로 확인할 수 있다.
const person = {name: 'Lee'};
// person 객체는 확장이 금지된 객체가 아니다.
console.log(Object.isExtensible(person)); // true
// person 객체의 확장을 금지하여 프로퍼티 추가를 금지한다.
Object.preventExtensions(person);
console.log(Object.isExtensible(person)); // false
// 프로퍼티 추가가 금지된다.
person.age = 20; // 무시. strict mode에서는 에러
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 메서드로 확인할 수 있다.
const person = {name:'lee'};
// person 객체를 밀봉된 객체가 아니다.
console.log(Object.isSealed(person)); // false
// person 객체를 밀봉하여 프로퍼티 추가,삭제,재정의를 금지한다.
Object.seal(person);
// 밀봉된 객체는 configurable이 false 다
console.log(Object.getOwnPropertyDescriptors(person));
person.age = 20; // 프로퍼티 추가 금지 무시된다.
console.log(perosn); {name:'lee'}
delete person.name; // 프로퍼티 삭제도 불가능 무시된다.
// 프로퍼티 재정의가 금지된다.
Object.defineProperty(person, 'name', {configurable: true});
객체 동결
Object.freeze 메서드는 객체를 동결시킨다. 동결된 객체는 읽기만 가능하다. 동결된 객체인지 여부는 Object.isFrozen 메서드로 확인할 수 있다.
const person = {name:'lee'};
// person 객체를 동결하여 프로퍼티 추가, 삭제, 재정의, 쓰기를 금지한다.
Object.freeze(person);
console.log(Object.getOwnPropertyDescriptors(person));
//
perosn.age = 20; // 추가 금지 무시된다.
delete person.name; // 삭제도 무시된다.
person.name = 'Kim'; // 값 갱신 무시된다.
// 프로퍼티 어트리뷰트 재정의도 금지된다.
Object.defineProperty(person, 'name', { configurable: true });
불변 객체
위에서 알아본 변경 방지 메서드들은 얕은 변경 방지로 직속 프로퍼티만 변경이 방지되고 중첩 객체까지는 영향을 주지는 못한다. 따라서 Object.freeze 메서드로 객체를 동결하여도 중첩 객체까지는 동결할 수 없다.
const person = {
name : 'lee',
address : {city : 'seoul'}
};
// 얕은 객체 동결
Object.freeze(person);
// 직속 프로퍼티만 동결한다.
console.log(Object.isFrozen(person)); // true
// 중첩 객체까지는 동결하지 못한다.
console.log(Object.isFrozen(person.address)); // false
따라서 중첩 객체까지 동결하여 변경이 불가능한 읽기 전용의 불변 객체를 구현하려면 객체를 값으로 갖는 모든 프로퍼티에 대해 재귀적으로 Object.freeze 메서드를 호출해야 한다.
function deepFreeze(target) {
if(target && typeof target === 'object' && !Object.isFrozen(target)) {
Object.freeze(target);
}
Object.keys(target).forEach(key => deepFreeze(target[key]));
}
const person = {
name : 'lee',
address: {city: 'seoul'}
};
deepFreeze(person);
console.log(Object.isFrozen(person)); // true
console.log(Object.isFrozen(person.address)); // true
'Front-End > JavaScript' 카테고리의 다른 글
모던 자바스크립트 Deep Dive - 생성자 함수에 의한 객체 생성(2) (0) | 2023.09.11 |
---|---|
모던 자바스크립트 Deep Dive - 생성자 함수에 의한 객체 생성 (1) | 2023.09.09 |
모던 자바스크립트 Deep Dive - let, const, 블록 레벨 스코프 (0) | 2023.09.01 |
모던 자바스크립트 Deep Dive - 전역변수 (1) | 2023.08.31 |
모던 자바스크립트 Deep Dive - 스코프 (0) | 2023.08.24 |