应网友的要求写的一个 对象属性访问器的判断

function Person(name) {
  this.name = name;
  this.flag = 0;
  Object.defineProperty(this, 'name', {
    get: function() { return name;},
    set: function(newName) {
      if (this.flag) {
        name = newName;
        this.flag = 0;
      }
      return name;
    }
  });
  this.setName = function(newName) {
    this.flag = 1;
    this.name = newName;
  }
};


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

manx.setName('jack');
console.log(manx.name); // 'jack'

  

posted @ 2017-07-03 20:02  ax=null  阅读(114)  评论(0编辑  收藏  举报