在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ defineProperty 訪問器屬性報(bào)錯 棧溢出

defineProperty 訪問器屬性報(bào)錯 棧溢出

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)行會報(bào)錯 Maximum call stack size exceeded

at Object.set [as year]

但是如果在year前面加個標(biāo)識符或者別的字母,就沒什么問題,哪位可以解答一下?

回答
編輯回答
安若晴

你給year定義了setter,然后在setter里面又給year賦值,就是又調(diào)用了setter,循環(huán)調(diào)用了

2018年5月18日 20:46
編輯回答
墻頭草

這種情況一般推薦使用閉包用于處理循環(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
2018年8月17日 12:10