2016-07-07 78 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; 
    } 
});