的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);
谁可以帮我,我很困惑,谢谢
答
您的基础属性不是writable
按https://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);
请说明你所期望的发生和实际发生的情况。 –
我希望this._year的价值是2005年 – Asen