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前面加个标识符或者别的字母,就没什么问题,哪位可以解答一下?

阅读 4.8k
3 个回答

这种情况一般推荐使用闭包用于处理循环调用

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

你给year定义了setter,然后在setter里面又给year赋值,就是又调用了setter,循环调用了

在对象对象属性[Getter/Setter]化之前定义一个变量就行

var book = {
    year:2004,
    edition:1
}

let temp=book.year //book = {    year:2004,    edition:1}

Object.defineProperty(book,"year",{
    get:function(){
        return temp
    },
    set:function(newVal){
        if(newVal>2004){
            temp = newVal ;
            this.edition += newVal - 2004 ;
        }
    }
});             //book = {    year:[Getter/Setter],    edition:1}
book.year = 2005 ;
console.log(book.edition)




撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题