[英]Property of this is undefined when used as Middleware
I have a Container class
: 我有一个Container class
:
// container.js
function Container(clients) {
this.clients = clients;
}
Container.prototype.test = function (req, res, next) {
console.log(this.clients['key']);
next();
};
module.exports = Container;
And then from another file I create an express server: 然后从另一个文件中创建一个快递服务器:
// server.js
const Express = require('express');
const BodyParser = require('body-parser');
const Container = require('./container');
var box = new Container({'key': 'secret' });
var app = new Express();
app.use(BodyParser.json());
app.use(box.test);
// some routes...
app.listen(3000);
When I make requests I get this logged to the console: 当我发出请求时,将其记录到控制台:
TypeError: Cannot read property 'key' of undefined
I'm so confused. 我很混乱。 I've read up on many different things about the improper use of this
but I can't see where I'm messing this up? 我已经阅读了许多关于不当使用this
不同信息,但看不到我在哪里弄乱了它?
Any ideas? 有任何想法吗?
When you get a function from the object app.use(box.test)
, it loses it's context and this
doesn't refer to the object
itself. 当您从对象app.use(box.test)
获得函数时,它会丢失上下文,而this
并不指向object
本身。 You need to use the bind()
function to create a function with attached context, or just use arrow function
and inside it call your function on the object. 您需要使用bind()
函数创建具有附加上下文的函数,或者仅使用arrow function
并在其内部在对象上调用您的函数。
app.use(() => box.test());
With bind
带bind
app.use(box.test.bind(box));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.