1.作用——监听变量的变化
Object.defineProperty():对对象的某个属性进行配置
Object.defineProperty(obj, prop, desc)
- obj 需要定义属性的当前对象
- prop 当前需要定义的属性名
- desc 属性描述符
1.1 get和set的配置
let Person = {}
let temp = null
Object.defineProperty(Person, 'name', {
get: function () {
return temp
},
set: function (val) {
temp = val
}
})
console.log(Person.name); //null
Person.name="ben";
console.log(Person.name); //ben
var a = { zhihu:0 };
Object.defineProperty(a, 'zhihu', {
get: function() {
console.log('get:' + zhihu);
return zhihu;
},
set: function(value) {
zhihu = value;
console.log('set:' + zhihu);
}
});
a.zhihu = 2; // set:2
console.log(a.zhihu); // get:2
// 2
1.2 configrable和enumerable
configrable 描述属性是否配置,以及可否删除
enumerable 描述属性是否会出现在for in 或者 Object.keys()的遍历中
let Person = {}
let temp = null
Object.defineProperty(Person, 'name', {
value:"benben",
writable:true,
configurable:false
})
delete Person.name; //不可删除
1.3 value和writable
value,默认值
writable:true 可改变,false不可改变
let Person = {}
Object.defineProperty(Person, 'name', {
value:"benben",
writable:true
})
console.log(Person.name); //benben
Person.name="ben";
console.log(Person.name); //ben
let Person = {}
Object.defineProperty(Person, 'name', {
value:"benben",
writable:false
})
console.log(Person.name); //benben
Person.name="ben";
console.log(Person.name); //benben
网友评论