Object.defineProperty 的使用

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

  

posted @ 2017-07-03 19:24  ax=null  阅读(128)  评论(0编辑  收藏  举报