The issue arises in the initial code snippet provided below, specifically when dealing with the object book
. Initially, the value of book.year
is set to 2013
. Even after updating the value by setting book.year = 2015
, retrieving the value using book.year
still returns 2013
instead of 2015
. The question remains - where am I making a mistake?
Below is the code snippet in question:
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;
//operations for evaluating the 'subscript' to add in this.edition
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" ;
}
//assignment operation for this.edition
var rawEdition = Number(this.edition.charAt(0)) + Number(diff);
this.edition = String(rawEdition) + subscript;
}
}
});
>>> book.year = 2015
>>>book.year //the output comes as 2013, but it should be 2015
In contrast, another similar code excerpt presented below showcases an expected behavior. When attempting to retrieve the value of book2.year
, and subsequently setting it as 2013
, the output correctly reflects 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 (In this instance, the output is as expected)