Object.defineProperty(obj, prop, descriptor)
const obj = {};
Object.defineProperty(obj, 'foo', {
__proto__: null,
value: 'bar'
writable: true
});
console.log(obj)
obj.foo = 1;
console.log(obj) // 안 바뀜, writable 불가
Object.defineProperty(obj, 'foo', {
__proto__: null,
value: 'foobar',
}); // CANNOT REDEFINE PROPERTY 에러, configurable이 false이기 때문
Object.defineProperty(obj, 'foo', {
writable: false;
}); // 단, writable 값만은 configurable == false 라도, 오직 false 로는 바뀔 수 있다
for(let i in obj) {
console.log(i)
}
Object.keys(obj)
// 둘 다 빈값으로 나옴, enumerable이 false이기 때문
const obj2 = {
foo: 'this is writable, enumerable, and configurable!!'
}
obj2.foo = 'is this writable, enumerable, and configurable ?'
console.log(obj2.foo)
// writable!!
for (let i in obj2) {
console.log(i)
}
console.log(Object.keys(obj2))
// enumerable!
Object.defineProperty(obj2, 'foo', {
value: '...'
}) // configurable !!
const obj2 = {
foo: 'bar'
}
// 는 다음과 같다.
Object.defineProperty(obj2, 'foo', {
value: 'bar',
writable: true,
enumerable: true,
configurable: true
})
const obj3 = {}
let temp = 0;
Object.defineProperty(obj3, 'foo', {
value: 0,
writable: true,
get (){
return temp;
}
});
// TypeError: Invalid property descriptor.
// Cannot both specify accessors and a value or writable attribute
function Archiver() {
let temp = null;
const archive = [];
Object.defineProperty(this, 'temp', {
get() {
console.log('get!');
return temp;
},
set(value) {
temp = value;
archive.push({ val: temp });
}
});
this.getArchive = () => archive;
}
const arc = new Archiver();
arc.temp = 'temp1';
arc.temp = 'temp2';
arc.getArchive();