javascript - 在快速中间件中调用时,这在原型函数中不起作用
问题描述
我在 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。
你能告诉我为什么在中间件中使用时这不起作用。
解决方案
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));
推荐阅读
- css - How to make a triangle shape with Tailwind?
- python - 保存多张图像
- firebase - Crashlytics 找不到 Google 服务生成的资源文件
- oauth-2.0 - 如何在没有服务器端渲染 CORS 问题的情况下使用 Oauth2.0
- sql - 如果 sql 表存在创建
- opengl - 调整大小时 GLFW 继续渲染
- sql - 在 SQL 中的情况下,两个不同的属性
- python - 均匀采样的 3D 网格网格
- android - 任务应用程序执行失败生成调试构建配置
- javascript - 在 Firefox 中通过 Selenium 访问 ShadowRoot 返回 JavascriptException: Cyclic object value