3

我收到有关此代码的最大调用堆栈大小的错误。

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

错误

RangeError: Maximum call stack size exceeded
4

1 回答 1

4

那是因为set每次分配发生时都会执行该函数。您正在定义递归代码。如果您定义了其他属性,authentication则不会出现该错误。

Object.defineProperty(ValueObject.prototype, "authentication", {
    get : function () {
        return this._authentication;
    },
    set : function (val) {
        this._authentication = val;
    }
});
于 2016-07-07T22:29:50.550 回答