为getter和setter定义对象属性

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

这是因为每次赋值发生时都会执行set函数。在您的代码中使用defineProperty没有意义。您正在定义预定义行为。 - Ram
1个回答

4

这是因为每次赋值时都会执行set函数。你正在定义一个递归代码。如果您定义的属性不是authentication,那么就不会出现该错误。

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

值得一提的是,异常RangeError:Maximum call stack size exceeded也会在获取操作时发生。 - Victor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接