Object.defineProperty
const object1 = {};
Object.defineProperty(object1, 'property1', {
value: 42,
writable: false
});
object1.property1 = 77;
// throws an error in strict mode
console.log(object1.property1);
// expected output: 42
为现有对象增加属性,还可以配置读写权限
let data2 = {}
data2._n = 0
Object.defineProperty(data2, 'n', {
get(){
return _n
}
set(value){
data2. _n = value
}
})
定义的属性 如果存在了,那么就干掉以前的重新创建一个