当类函数传递到快速路由器时会丢失上下文

时间:2018-12-17 22:14:07

标签: javascript node.js express ecmascript-6 this

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

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

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

0 个答案:

没有答案