Object define property for getter and setter

橙三吉。 提交于 2020-01-02 13:56:42

问题


I'm getting an error on Maximum call stack size for this code.

function ValueObject() {
}

ValueObject.prototype.authentication;

Object.defineProperty(ValueObject.prototype, "authentication", {
    get : function () {
        return this.authentication;
    },
    set : function (val) {
        this.authentication = val;
    }
});

var vo = new ValueObject({last: "ac"});
vo.authentication = {a: "b"};
console.log(vo);

Error

RangeError: Maximum call stack size exceeded

回答1:


That's because the set function is executed each time the assignment happens. You are defining a recursive code. If you define a different property other than authentication then you don't get that error.

Object.defineProperty(ValueObject.prototype, "authentication", {
    get : function () {
        return this._authentication;
    },
    set : function (val) {
        this._authentication = val;
    }
});


来源:https://stackoverflow.com/questions/38256087/object-define-property-for-getter-and-setter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!