【问题标题】:Nodejs Maximum call stack size exceededNodejs 超出最大调用堆栈大小
【发布时间】:2020-03-20 11:34:09
【问题描述】:

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

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;

}

我做错了什么?

【问题讨论】:

    标签: javascript node.js class


    【解决方案1】:

    您的active 属性是一个访问器属性,并且您在它自己的setter 中分配给它。这会再次调用 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 主体中的方法定义后面没有 ;。 (语言语法允许; 存在,但它不应该存在。)

    【讨论】:

      猜你喜欢
      • 2019-07-05
      • 2017-09-02
      • 2014-02-07
      • 2017-07-02
      • 1970-01-01
      • 2020-11-16
      • 2013-08-18
      • 1970-01-01
      • 2015-10-24
      相关资源
      最近更新 更多