자바스크립트 엔진은 프로퍼티를 생성할 때 프로퍼티의 상태를 나타내는 프로퍼티 어트리뷰트를 기본값으로 자동 정의한다. 프로퍼티의 상태란 프로퍼티의 값(value), 값의 갱신 가능 여부(writable), 열거 가능 여부(enumerable), 재정의 가능 여부(configurable)를 말한다.
const person = {
name : 'Lee'
};
console.log(Object.getOwnPropertyDescriptor(person, 'name'));
// {value : 'Lee', writable: true, enumerable: true, configurable : true}
프로퍼티 어트리뷰트는 자바스크립트 엔진이 관리하는 내부 상태 값인 내부 슬록 [[Value]], [[Writable]], [[Enumerable]], [[Configurable]]이다. 따라서 프로퍼티 어트리뷰트에 직접 접근할 수 없지만 Object.getOwnPropertyDesciptor 메서드를 사용하여 간접적으로 확인할 수는 있다.
const person = {
name : 'Lee'
}
// 프로퍼티 동적 생성
person.age = 20;
console.log(Object.getOwnPropertyDescriptors(person));
//{ name : {value: 'lee', writable: true, enumerable:true, configurable: true}, age:{value: 20, writable: true, enumerable:true, configurable: true}}
프로퍼티는 데이터 프로퍼티와 접근자 프로퍼티로 구분할 수 있다.
• 데이터 프로퍼티 : 키와 값으로 구성된 일반적인 프로퍼티다. 지금까지 살펴본 모든 프로퍼티는 데이터 프로퍼티다.
• 접근자 프로퍼티 : 자체적으로는 값을 갖지 않고 다른 데이터 프로퍼티의 값을 읽거나 저장할 때 호출되는 접근자 함수로 구성된 프로퍼티다.
const person = {
firstName: "sangdon",
lastName: "Lee",
// 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);
// 접근자 프로퍼티를 통한 값의 저장
// setter 함수가 호출됨.
person.fullName = "Lee gangdon";
console.log(person);
// 접근자 프로퍼티를 통한 프로퍼티 값의 참조
// getter 함수가 호출됨.
console.log(person.fullName);
Object.defineProperty 메서드를 사용하면 프로퍼티의 어트리뷰트를 정의할 수 있다.
const person = {}
// 데이터 프로퍼티 정의
Object.defineProperty(person, 'firstName',{
value:'Sangdon',
writable:true,
enumerable:true,
configurable:true
});
// 디스크립터 객체의 프로퍼티를 누락시키면 undefined, false가 기본값이다.
Object.definedProperty(person, 'lastName',{
value : 'Lee'
});
let descriptor = Object.getOwnPropertyDescriptor(person, 'firstName');
console.log(descriptor);
// {value: 'Sangdon', writable:true, enumerable:true, configurable:true}
descriptor = Object.getOwnPropertyDescriptor(person, 'lastNmae');
console.log(descriptor);
// {value:"Lee", writable:false, enumerable:false, configurable:false}
// lastName 프로퍼티는 [[Enumberable]]의 값이 fasle이므로 열거되지 않는다.
console.log(Object.keys(person)); // ["firstName"}
person.lastName : 'Kim'; // lastName 프로퍼티는 [[Writable]]의 값이 false이므로 값을 변경할 수 없다. 에러는 발생하지 않고 무시된다.
delete person.lastName // lastName 프로퍼티는 [[Configurable]]값이 false이므로 삭제할 수 없다. 에러는 발생하지 않고 무시된다.
자바스크립트는 객체의 변경을 방지하는 다양한 메서드를 제공한다. 객체 변경 방지 메서드들은 객체의 변경을 금지하는 강도가 다르다.
Object.preventExtensions 메서드는 객체의 확장을 금지한다. 즉, 확장이 금지된 객체는 프로퍼티 추가가 금지된다.
확장이 가능한 객체인지 여부는 Object.isExtensible 메서드로 확인할 수 있다.
const person4 = {
name: "Lee",
};
console.log(Object.isExtensible(person4)); // true
//확장 금지 구문
Object.preventExtensions(person4);
console.log(Object.isExtensible(person4)); // false
person4.age = 26;
console.log(person4); // {name : "Lee"}
//삭제는 가능하다.
delete person4.name;
console.log(person4); // {}
Object.defineProperty(person4, "age", { value: 26 }); // TypeError: Cannot define property age, object is not extensible
Object.seal 메서드는 객체를 밀봉한다. 객체 밀봉이란 프로퍼티 추가 및 삭제와 프로퍼티 어트리뷰트 재정의 금지를 의미한다. 즉, 밀봉된 객체는 읽기와 쓰기만 가능하다.
const person5 = {
name: "Lee",
};
console.log(Object.isSealed(person5)); // false
// 객체 밀봉 구문
Object.seal(person5);
console.log(Object.isSealed(person5)); // true
// 밀봉된 객체는 configurable이 false다.
console.log(Object.getOwnPropertyDescriptor(person5, "name")); // { value: 'Lee', writable: true, enumerable: true, configurable: false }
// 프로퍼티 추가가 금지된다.
person5.age = 26;
console.log(person5); // {name : 'Lee'}
// 프로퍼티 삭제가 금지된다.
delete person5.name;
console.log(person5); // {name : 'Lee'}
// 프로퍼티 값 갱신은 가능하다.
person5.name = "Kim";
console.log(person5); // {name : 'Kim'}
// 프로퍼티 어트리뷰트 재정의가 금지된다.
Object.defineProperty(person5, "name", { configurable: true }); //TypeError: Cannot redefine property: name
Object.freeze 메서드는 객체를 동결한다. 객체 동결이란 프로퍼티 추가 및 삭제와 프로퍼티 어트리뷰트 재정의 금지, 프로퍼티 값 갱신 금지를 의미한다. 즉, 동결된 객체는 읽기만 가능하다.
const person6 = {
name: "Lee",
};
console.log(Object.isFrozen(person6)); //false
Object.freeze(person6);
console.log(Object.isFrozen(person6)); //true
// 동결된 객체는 writable과 configurable이 false다.
console.log(Object.getOwnPropertyDescriptor(person6, "name")); //{value: 'Lee', writable: false, enumerable: true, configurable: false}
// 프로퍼티 추가가 금지된다.
person6.age = 26;
console.log(person6); // {name : 'Lee'}
//프로퍼티 삭제가 금지된다.
delete person.name;
console.log(person6); // {name : 'Lee'}
// 프로퍼티 값 갱신이 금지된다.
person6.name = "Kim";
console.log(person6); // {name : 'Lee'}
//프로퍼티 어트리뷰트 재정의가 금지된다.
Object.defineProperty(person6, "name", { configurable: true }); // TypeError: Cannot redefine property: name