简体   繁体   中英

Nodejs Maximum call stack size exceeded

I'm receiving the above error at this line set active(val) of the following code:

middleware.js

class middleware {

    constructor(){
        this.active = false;
    };

    set active(val) {
        this.active = val;
    };

    get active(){
        return this.active;
    };

}

module.exports = middleware

routes.js

const middleware = require('../middleware')

router.get("/start", passport.authenticate('jwt', { failureRedirect: '/login' }), (req, res) => {

    var mw = new middleware()
    mw.active = true;

}

What am i doing wrong?

Your active property is an accessor property , and you're assigning to it in its own setter. That invokes the setter again, which invokes the setter again, etc.

If you want active to be an accessor property, you need to store the value elsewhere. These days, you can use a private field in modern versions of Node.js:

class middleware {
    #active = false;

    constructor(){
    }

    set active(val) {
        this.#active = val;
    }

    get active(){
        return this.#active;
    }
}

Or just another property:

class middleware {
    constructor(){
        this._active = false;
    }

    set active(val) {
        this._active = val;
    }

    get active(){
        return this._active;
    }
}

Or make active a data property:

class middleware {
    constructor(){
        this.active = false;
    }
}

Side note: Method definitions in class bodies don't have ; after them. (A ; is tolerated there by the language grammar, but it's not supposed to be there.)

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