javascript - 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;
}
我究竟做错了什么?
解决方案
您的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 存在,但它不应该存在。)
推荐阅读
- google-apps-script - 谷歌表格不断扩展数组公式
- php - PHP在循环中重复相同的功能是否很好?
- javascript - 前提条件检查后如何显示对话框?
- c# - 如何修复此错误:“无法跟踪实体类型的实例...”
- javascript - 在具有相同属性值的对象中显示最新条目
- css - 语义固定菜单将容器移动到页面顶部
- jquery - 复选框将值添加到表中的下一个输入
- r - 是否有更短的方法在 R 的回归中使用滞后运算符
- c# - 调用 ShutdownAsync() 后如何重新启动 gRPC 服务器;在 C# 下?
- java - 我如何将这个 for each 转换为 for 循环?