我在 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
中的快速中间件调用 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。
你能告诉我为什么这个在中间件中使用时不起作用。
最佳答案
app.get
行的调用上下文是 app
,因此当 b
函数尝试运行 this.c("asdsad");
时,它会在您实际尝试访问 test_ob.c
时尝试访问 app.c
。
将 b
函数传递给 app.get
时,将 b
函数的 this
值绑定(bind)到 test_ob
,以便正确引用它:
app.get('/testAPI',test_ob.b.bind(test_ob));
关于javascript - 在快速中间件中调用时,这在原型(prototype)函数中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50198812/