Object.defineProperty

  1. const object1 = {};
  2. Object.defineProperty(object1, 'property1', {
  3. value: 42,
  4. writable: false
  5. });
  6. object1.property1 = 77;
  7. // throws an error in strict mode
  8. console.log(object1.property1);
  9. // expected output: 42

为现有对象增加属性,还可以配置读写权限

  1. let data2 = {}
  2. data2._n = 0
  3. Object.defineProperty(data2, 'n', {
  4. get(){
  5. return _n
  6. }
  7. set(value){
  8. data2. _n = value
  9. }
  10. })

定义的属性 如果存在了,那么就干掉以前的重新创建一个