JavaScript 对象定义属性不起作用

Cel*_*aro 1 javascript javascript-objects

所以我了解到在Javascript中我们可以使用defineProperties来定义对象的多个属性。因此,我在下面的简单代码中尝试了它,但我并没有安静地得到我想要的结果。访问器似乎不起作用,我不知道为什么。

var book = {};
Object.defineProperties(book,{
 _year: {
    value: 2004 },
 edition: {
    value: 1},
 year: {
    get: function(){
    this._year;},
    set: function(value){
    if(value>2004){
     this._year = value;
     this.edition = this.edition + value - 2004;
 });
 this.year = 2016;
 alert(book.edition); //1 why??
Run Code Online (Sandbox Code Playgroud)

t.n*_*ese 5

您的代码中有多个错误,但主要问题是,如果您定义一个属性,value则默认情况下它是只读的:

MDN:Object.defineProperty

writable当且仅当与属性关联的值可以通过赋值运算符更改时
为 true 。
默认为false

您需要添加writable: true以使这些属性可写。

因此,您的代码必须如下所示(包括纠正您遇到的所有其他错误):

var book = {};
Object.defineProperties(book, {
  _year: {
    value: 2004,
    writable: true // << writable
  },
  edition: {
    value: 1,
    writable: true // << writable
  },
  year: {
    get: function() {
      // << missing return
      return this._year;
    },
    set: function(value) {

      if (value > 2004) {
        this._year = value;
        this.edition = this.edition + value - 2004;
      }
    }
  }
});
book.year = 2016; // << here you used this instead of book
console.log(book.edition);
Run Code Online (Sandbox Code Playgroud)