为了账号安全,请及时绑定邮箱和手机立即绑定

defineProperty 访问器属性报错 栈溢出

defineProperty 访问器属性报错 栈溢出

喵喵时光机 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)如上所示,直接运行会报错 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


查看完整回答
反对 回复 2019-03-29
?
ITMISS

TA贡献1871条经验 获得超8个赞

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


查看完整回答
反对 回复 2019-03-29
  • 2 回答
  • 0 关注
  • 766 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号