首页 > 解决方案 > 类函数在传递到快速路由器时会丢失上下文

问题描述

我最近为一个应用程序编写了一个小型访问控制模块。后端是带快递的节点。模块如下

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

如果我将模块直接导入到路由中,一切都按预期工作,我只想知道为什么我的类函数会丢失上下文,即使我将它们绑定在构造函数中。有没有办法防止这种情况?

标签: javascriptnode.jsexpressecmascript-6this

解决方案


推荐阅读