javascript - ES6 类,传递函数作为参数来注册 expressjs 路由

标签 javascript ecmascript-6

此类用于扩展我的 expressjs 应用程序中的所有 Controller :

import response from '../utils/responseParser.js';

const APISLUG = '/api/v1/';

export default class BaseController {

  constructor(name, app, model){
    this.model = model;
    this.app = app;
    this.name = name;
    console.log(model);
    this.register();
  }

  register() {
    this.app.get(APISLUG + this.name, this.all);
  }
  /*
  Retrive all records
  */
  all(req, res, next) {
    this.model.all(req.body, (err, data) => {
      if(err) return res.json(response.replyError(data));
      return res.json(response.reply(data));
    });
  }
}

如您所见,我已经创建了一个“注册”方法来自动设置所有基本路由。

我在这一行收到错误unable to read property "model "of undefined ":

this.app.get(APISLUG + this.name, this.all);

我认为这是因为当我将函数作为参数传递时范围丢失了。我该如何解决这个问题?

最佳答案

使用bind绑定(bind)作用域的方法,像这样

this.app.get(APISLUG + this.name, this.all.bind(this));

关于javascript - ES6 类,传递函数作为参数来注册 expressjs 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35814872/

相关文章:

javascript - JS 对象属性继承

javascript - 改变javascript中标签的值?

javascript - 单击时未选择 HTML 输入

javascript - 我的 DOM 中的 Google Analytics(分析)像素在哪里?

javascript - JS如何过滤数组中顶部索引处的匹配元素

javascript - ngCache与Webpack,ES6不输出模板html,解析错误

javascript - 触发器与 ref react dropzone 不起作用

javascript - JQuery 和 Fancybox 单击图像打开新页面/链接(更新现有代码)

javascript - 在 contentEditable div 中插入元素之后设置插入符位置

javascript - 如何使用 jquery 选择器在 ECMA 6 中的类中定义事件?