JS——Object.defineProperty()

2019-04-22  本文已影响0人  benbensheng

深入浅出Object.defineProperty()

1.作用——监听变量的变化

Object.defineProperty():对对象的某个属性进行配置
Object.defineProperty(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


上一篇下一篇

猜你喜欢

热点阅读