javascript - 类函数在传递到快速路由器时会丢失上下文
问题描述
我最近为一个应用程序编写了一个小型访问控制模块。后端是带快递的节点。模块如下
class Rbac {
constructor() {
if (!Rbac.instance) {
Rbac.instance = this;
}
this.rbacStructure = {};
this.init = this.init.bind(this);
this.checkPermission = this.checkPermission.bind(this);
this.checkPermissionSync = this.checkPermissionSync.bind(this);
this.checkPermissionMiddleware = this.checkPermissionMiddleware.bind(this);
this.doesPermissionExistInGroup = this.doesPermissionExistInGroup.bind(
this
);
this.instance = this;
return Rbac.instance;
}
.
.
.
.
.
.
const instance = new Rbac();
Object.freeze(instance);
export default instance;
在我的 app.js 中,我想将对象的实例传递给路由器,如下所示
import Rbac from "./helpers/rbac";
import settingRouteExport from "./routes/settingRoutes";
const settingsRoutes = settingRouteExport(Rbac);
app.use("/settings", settingsRoutes);
我正在尝试在 settingRoutes 中使用它,如下所示
import express from "express";
const router = express.Router();
// Exporting the function that returns the router
export default (Rbac) => {
.
.
.
.
.
router.get(
"/users",
Rbac.checkPermissionMiddleware(["canCreateUser", "canEditUser"]),
UserControllers.getUsers
);
.
.
.
.
.
return router;
};
即使我将类函数绑定到对象,我仍然收到以下错误
TypeError: Cannot read property 'checkPermissionMiddleware' of undefined
如果我将模块直接导入到路由中,一切都按预期工作,我只想知道为什么我的类函数会丢失上下文,即使我将它们绑定在构造函数中。有没有办法防止这种情况?
解决方案
推荐阅读
- c# - goto - 不在范围内(C#)
- ruby-on-rails - RSpec + Capybara 范围界定返回意外结果
- javascript - js 翻转卡中的故障 - 翻转
- r - How to compare each row of dataframe 1 with each of dataframe 2 and sum up if the values are the same?
- sql - 插入前的 SQL 触发器,将新的工作日期与上一个日期进行比较
- javascript - 如何在映射数组期间从列表中显示元素一次
- c++ - 这对编译器优化安全吗?
- php - 过滤来自 mysql 查询的结果
- r - ShinyAction 按钮关闭应用程序,但绕过 session$onSessionEnded
- android - 如何使用 Android uiautomator 查找元素?