不更新属性值的二传手函数

Setter function not updating property values

本文关键字:二传手 函数 更新 属性      更新时间:2023-09-26

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显示旧的属性值,即使资源库应该更新属性?

使属性可写,因为可写的默认值是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);