javascript - 如何避免用作快速路由回调的函数中的 'this' 问题

标签 javascript node.js express this

我正在尝试编写一个为快速路线创建通用处理程序的模块

例如

//create a new route handler with some config
//every routeHanlder method needs to be able to access this config
var handler = new routeHandler({config: "value"});

//handle a get route ("Example 1")
app.get('route', handler.read)

//handle a get route with params ("Example 2")
app.get('route.:id', function(req, res){
    handler.read(req,res,{query: {_id: req.params.id}});
});

我在使“示例 1”工作时遇到问题...

app.get('route', handler.read)

...因为我在 handler.read 中丢失了“this”的值

我理解为什么“this”的值不同,但我不知道如何使其工作,或者不使用“this”而获得所需结果的另一种方法。

这是一个笨蛋 link

总结我正在尝试找到一种方法,使我的routeHandler对象(参见上面的plunker和下面的代码粘贴)在用作快速路由的回调时工作(参见上面的“示例1”)。

var routeHandler = function(config){

  if (!(this instanceof(routeHandler))) {
      return new routeHandler(config);
  }

    config = config || {};

    if(config.configData){

      this.configData = config.configData;

    }

};

routeHandler.prototype = {
  read: function(req, res, options){

    //The problem: accessing configData without using this
    console.log("inside callback", this, this.configData);

    options = options || {};

  }
};

编辑:我希望能够使用不同的配置数据创建路由处理程序的多个实例,例如

var handlerOne = new RouteHandler("configDataOne"); 
var handlerTwo = new RouteHandler("configDataTwo"); 

app.get('/firstRoute', handlerOne.read); 
app.get('/secondRoute', handlerTwo.read);

最佳答案

您可以将routeHandler的configData保存在express对象“app”中,如下所示:

app.set("routeHandlerConfigData", "identifier or whatever value you want to store");

然后让你的routeHandler成为一个简单的中间件

var routeHandler = function(req, res, next){
  var configData = req.app.get("routeHandlerConfigData");
  //Do whatever you want
};

关于javascript - 如何避免用作快速路由回调的函数中的 'this' 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26971234/

相关文章:

javascript - 无法获取所选选择标签的标签文本

Javascript 数组按多条件排序

javascript - 创建具有可变属性的对象

javascript - 无法使用 Selenium webdriver、python 在 <span> 标记内模拟 onclick javascript

javascript - 如何从android webview获取Vimeo视频的播放进度?

node.js - "mpromise (mongoose' s 默认 promise 库)已弃用“测试时出现错误

Node.js REPL 延续行

javascript - 在node.js程序的全局范围内使用 'var'和 'this'

angularjs - 使用 Angular 和 Express 进行客户授权

node.js - 在不启动服务器的情况下对 Express/Loopback 中间件进行单元测试