首页 > 解决方案 > Nodejs 超出最大调用堆栈大小

问题描述

我在set active(val)以下代码的这一行收到上述错误:

中间件.js

class middleware {

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

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

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

}

module.exports = middleware

路由.js

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

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

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

}

我究竟做错了什么?

标签: javascriptnode.jsclass

解决方案


您的active属性是一个访问器属性,并且您在它自己的设置器中分配给它。这会再次调用 setter,然后再次调用 setter,等等。

如果您想active成为访问器属性,则需要将值存储在其他地方。如今,您可以在现代版本的 Node.js 中使用私有字段:

class middleware {
    #active = false;

    constructor(){
    }

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

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

或者只是另一个属性:

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

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

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

或者创建active一个数据属性:

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

旁注:class主体中的方法定义在;它们之后没有。(;语言语法允许 A 存在,但它不应该存在。)


推荐阅读