1. 程式人生 > >Object.defineProperty 的使用

Object.defineProperty 的使用

brush name person pre ret define turn class bject

function Person(name) {
  this.name = name;

  Object.defineProperty(this, ‘name‘, {
    get: function() { return name;},
    set: function(newName) {
      if (name) { return;}
      return name = newName;
    }
  });
}

var manx = new Person(‘manx‘);
manx.name = ‘bob‘;
console.log(manx.name); // manx;

var smith = new Person(‘smith‘);
console.log(smith.name); // smith

  

Object.defineProperty 的使用