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;
    }
})

  

 

原文地址:https://www.cnblogs.com/lonecloud/p/7457228.html