簡體   English   中英

用於getter和setter的對象定義屬性

[英]Object define property for getter and 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

這是因為每次分配發生時都會執行set函數。 您正在定義一個遞歸代碼。 如果您定義了authentication以外的其他屬性,則不會收到該錯誤。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM