在下面给出的对象为book
的第一个代码中,开头book.year
设置为2013
。当我分配book.year = 2015
并再次尝试通过执行book.year
检索其值时,我仍然得到2013
而不是2015
。我在哪里做错了?
代码如下:
var book = {};
Object.defineProperties(book, {
_yearOrigin: {
value: 2013
},
edition: {
value: "1st"
},
year: {
get: function(){return this._yearOrigin},
set: function(newValue){
//assigning this._yearOrigin
this._yearOrigin = newValue;
//carrying the operation for evaluating the `subscript` to add in this.edition
//diff = difference in year
var diff = String(newValue - 2013);
var diffLast2ndChar = diff.charAt(diff.length - 2);
var diffLastChar = diff.charAt(diff.length - 1);
var subscript = "";
if (diff.length > 1 && diffLast2ndChar == "1") {
subscript = "th";
} else {
subscript = diffLastChar == "1"
? "st"
: diffLastChar == "2"
? "nd"
: diffLastChar == "3"
? "rd"
: "th" ;
}
//--end of subscript evaluation
//assigment operation of this.edition
var rawEdition = Number(this.edition.charAt(0)) + Number(diff);
this.edition = String(rawEdition) + subscript;
}
}
});
>>> book.year = 2015
>>>book.year //output is 2013 , but expected output is 2015
然而,相反,在尝试检索book2.year
的值时,在下面给出的另一个等效代码段中,在分配book2.year = 2013
后,按预期提供输出2013
var book2 = {
_year: 2004,
edition: 1
};
Object.defineProperty(book2, "year", {
get: function(){
return this._year;
},
set: function(newValue){
if (newValue > 2004) {
this._year = newValue;
this.edition += newValue - 2004;
}
}
});
book2.year = 2005;
console.log(book2.year); //2005 (Now this time the output is expected unlike in the previous code shown above)
答案 0 :(得分:0)
我忽略了“当使用Object.Property/Object.properties
定义对象属性时,默认writable
到false
,即定义的值无法更改(非可写)“评论部分的人提到了这一点。
当我添加writable = true
,如下所示,然后问题得到解决,预期结果弹出
_yearOrigin: {
value: 2013,
writable: true
},