【问题标题】:Object define property for getter and setter对象为 getter 和 setter 定义属性
【发布时间】:2016-07-07 22:11:08
【问题描述】:

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

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 毫无意义。您定义的是预定义的行为。

标签: javascript defineproperty


【解决方案1】:

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

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

【讨论】:

  • 值得一提的是异常RangeError: Maximum call stack size exceeded也发生在get操作上
猜你喜欢
  • 2012-01-31
  • 2014-07-04
  • 2022-12-24
  • 2012-09-09
  • 2010-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多