如何使用Object.defineProperties()?

时间:2018-11-13 19:09:27

标签: javascript

下面,我尝试使用defineProperties函数定义对象的属性,但是在此脚本中打印最后一行时,我得到了意外的结果。我希望2005年会在控制台上记录下来,但我会一直得到2004年。同样适用于其他属性,例如版本。我在使用这个defineProperties吗  功能不正确?

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;
      }
    }
  }
});


console.log(book);
console.log(book.year);

book.year = 2005;

console.log(book);
console.log(book.year);

1 个答案:

答案 0 :(得分:2)

您将_year定义为只读,因此this._year = newValue失败(无提示)。您需要使其可写。

  _year: {
    value: 2004,
    writable: true
  },
相关问题