js使用defineProperty的一些坑

var p2={

};
Object.defineProperty(p2,"gs",{
    get:function () {
        return this.gs;
    },
    set:function (gs) {
        this.gs=gs;
    }
})

写了一段如上low的代码,然后再浏览器运行

alert(p2.gs);后浏览器报错了

Uncaught RangeError: Maximum call stack size exceeded

 错误详情:

由于在js中

调用的是由于其p2.gs调用的其实是gs.get方法,由于在函数内部this.gs调用的还是gs.get方法,导致其一直在循环调用,最后堆栈报错了

解决办法:

var p2={
    _gs:123
};
Object.defineProperty(p2,"gs",{
    get:function () {
        return this._gs;
    },
    set:function (gs) {
        this._gs=gs;
    }
})

  

 

 

posted @ 2017-08-31 11:01  lonecloud  阅读(919)  评论(0编辑  收藏  举报
我的博客即将同步至 OSCHINA 社区,这是我的 OSCHINA ID:lonecloud,邀请大家一同入驻:https://www.oschina.net/sharing-plan/apply