var book = { year:2004, edition:1}Object.defineProperty(book,"year",{ get:function(){ return this.year }, set:function(newVal){ if(newVal>2004){ this.year = newVal ; this.edition += newVal - 2004 ; } }});book.year = 2005 ;console.log(book.edition)如上所示,直接运行会报错 Maximum call stack size exceededat Object.set [as year]但是如果在year前面加个标识符或者别的字母,就没什么问题,哪位可以解答一下?
2 回答

心有法竹
TA贡献1866条经验 获得超5个赞
这种情况一般推荐使用闭包用于处理循环调用
var book = {
year:2004,
edition:1
}
function proxy(obj, prop) {
let val= obj[prop];
Object.defineProperty(obj,prop,{
get:function(){
return val;
},
set:function(newVal){
if(newVal>2004){
val = newVal
this.edition += newVal - 2004 ;
}
}
});
}
proxy(book, 'year');
book.year = 2005;
// this.edition => 2
添加回答
举报
0/150
提交
取消