首页 > 解决方案 > 在快速中间件中调用时,这在原型函数中不起作用

问题描述

我在 node.js express 框架中遇到了一个奇怪的错误。

我创建了一个说test.js的文件,其中包含以下代码

function a(){

}

a.prototype.b = function(){
    this.c("asdsad");
}

a.prototype.c = function(string){
    console.log("ccc"+string)
}

/*var ob = new a();
ob.b();*/

module.exports = a;

和另一个文件call_test.js

var test = require('./test');
var test_ob = new test();
test_ob.b();

当我运行 node call_test.js 时,它给了我正确的输出 cccasdsad

但是,当我在文件express_test.js中使用 express 中间件调用 test.js 时

var express = require("express");
var app = express();
var test = require('./test');
var test_ob = new test();

app.get('/testAPI',test_ob.b);

当我点击 testAPI 时,我收到错误 this.c is not a function。

你能告诉我为什么在中间件中使用时不起作用。

标签: javascriptnode.jsexpressthisprototype

解决方案


The calling context of your app.get line is app, so when the b function tries to run this.c("asdsad");, it's trying to access app.c when you're actually trying to access test_ob.c.

When passing the b function to app.get, bind the b function's this value to the test_ob so it will be referenced properly:

app.get('/testAPI',test_ob.b.bind(test_ob));

推荐阅读