喵喵時(shí)光機(jī)
2019-03-13 13:13:56
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)如上所示,直接運(yùn)行會(huì)報(bào)錯(cuò) Maximum call stack size exceededat Object.set [as year]但是如果在year前面加個(gè)標(biāo)識(shí)符或者別的字母,就沒什么問題,哪位可以解答一下?
2 回答

心有法竹
TA貢獻(xiàn)1866條經(jīng)驗(yàn) 獲得超5個(gè)贊
這種情況一般推薦使用閉包用于處理循環(huán)調(diào)用
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

ITMISS
TA貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超8個(gè)贊
添加回答
舉報(bào)
0/150
提交
取消