在<>这本书中,发现js用defineProperties方法同时定义多个属性,发现

hell_henry 2017-09-24 05:52:25
在<<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;

而且在严格模式下却会报错!!! 求好心的大侠解答!!
...全文
170 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
天际的海浪 2017-09-24
  • 打赏
  • 举报
回复
严格模式下报错说的很清楚啊,defineProperties添加的属性默认是只读的

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);

87,901

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧