的javascript:为什么代码没有工作

的javascript:为什么代码没有工作

问题描述:

首先,这是我的javascript代码的javascript:为什么代码没有工作

<script type="text/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 = 2005; 
alert(book.edition); 
alert(book._year); 

enter image description here

enter image description here

谁可以帮我,我很困惑,谢谢

+0

请说明你所期望的发生和实际发生的情况。 –

+0

我希望this._year的价值是2005年 – Asen

您的基础属性不是writablehttps://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties

以下工作:

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; 
 
console.log(book.edition); 
 
console.log(book._year);

+1

非常感谢! – Asen

+0

没问题,乐意帮忙! – G0dsquad