defineProperty 访问器属性报错 栈溢出

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 exceeded


at Object.set [as year]

但是如果在year前面加个标识符或者别的字母,就没什么问题,哪位可以解答一下?


喵喵时光机
浏览 767回答 2
2回答

心有法竹

这种情况一般推荐使用闭包用于处理循环调用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

你给year定义了setter,然后在setter里面又给year赋值,就是又调用了setter,循环调用了
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript