Setter函数不更新属性值

时间:2015-06-12 02:57:50

标签: javascript



var book = {};
Object.defineProperties(book, {
  _year: {
    value: 2004
  },
  edition: {
    value: 1
  },
  year: {
    get: function() {
      return this._year;
    },
    set: function(newValue) {
      if (newValue > 2004) {
        this._year = newValue;
        this.edition += newValue - 2004;
      }
    }
  }
});
book.year = 2006;
alert(book.year); // 2004
alert(book.edition); // 1




为什么alert显示旧的属性值,即使setter应该更新属性?

1 个答案:

答案 0 :(得分:2)

使properties可写为可写的默认值为false

var book = {};
Object.defineProperties(book, {
  _year: {
    value: 2004,
    writable: true
  },
  edition: {
    value: 1,
    writable: true
  },
  year: {
    get: function() {
      return this._year;
    },
    set: function(newValue) {
      if (newValue > 2004) {
        this._year = newValue;
        this.edition += newValue - 2004;
      }
    }
  }
});
book.year = 2006;
alert(book.year);
alert(book.edition);