简体   繁体   中英

Object define property for getter and setter

I'm getting an error on Maximum call stack size for this code.

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);

Error

RangeError: Maximum call stack size exceeded

That's because the set function is executed each time the assignment happens. You are defining a recursive code. If you define a different property other than authentication then you don't get that error.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM