2016-07-07 77 views
0

我在此代码的最大调用堆栈大小上遇到错误。对象为getter和setter定义属性

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 
+0

这是因为'set'函数每次执行任务时都会执行。在代码中使用'defineProperty'没有意义。你所定义的是预定义的行为。 – undefined

回答

0

,由于set功能在每次转让发生时执行的。你正在定义一个递归代码。如果您定义除authentication以外的其他属性,则不会出现该错误。

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