在<<javascript高级程序设j计>>这本书中,
发现js用defineProperties方法同时定义多个属性,
发现一些不合理的问题:
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=2004;
console.log(book.year);
console.log(book.edition);
为什么输出结果book.year会是2004而不是2004;
book.edition会是1而不是2;而且在严格模式下却会报错!!! 求好心的大侠解答!!
发现js用defineProperties方法同时定义多个属性,
发现一些不合理的问题:
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=2004;
console.log(book.year);
console.log(book.edition);
为什么输出结果book.year会是2004而不是2004;
book.edition会是1而不是2;而且在严格模式下却会报错!!! 求好心的大侠解答!!
var book={};
Object.defineProperties(book,{
_year:{
value:2004,
writable: true //当且仅当该属性的 writable 为 true 时,该属性才能被赋值运算符改变。默认为 false。
},
edition:{
value:1,
writable: true //当且仅当该属性的 writable 为 true 时,该属性才能被赋值运算符改变。默认为 false。
},
year:{
get:function(){
return this._year;
},
set:function(newValue){
if(newValue>2004){
this._year = newValue;
this.edition+=newValue -2004;
}
}
}
});
book.year=2005;
console.log(book.year);
console.log(book.edition);