代碼如下 , 問題,為啥_year屬性沒有改變呢?
var book = {};
Object.defineProperties(book , {
_year: {
value: 2004
},
edition: {
value: 1
},
year: {
get: function(){
return this._year;
},
set: function(newValue){
// alert(newValue);
if(newValue > 2004){
this._year = newValue;
alert(this._year);
this.edition += newValue - 2004;
}
}
}
});
book.year = 2015;
alert(book.year); //2004
alert(book.edition); //1
默認是不可以修改的,自己好好看看:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties
var book = {};
Object.defineProperties(book, {
_year: {
value: 2004,writable:true//設置為可寫入,默認flase
},
edition: {
value: 1, writable: true//設置為可寫入,默認flase
},
year: {
get: function () {
return this._year;
},
set: function (newValue) {
if (newValue > 2004) {
this._year = newValue;
this.edition += newValue - 2004;
}
}
}
});
book.year = 2015;
alert(book.year);
alert(book.edition);