简体   繁体   English

用作中间件时,此属性的属性未定义

[英]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.

相关问题 在类方法中使用时,类中的属性未定义 - Property in class is undefined when used in class method Jest fn 用作 object 属性时未定义 - Jest fn undefined when used as an object property 将字符串用作输入名称时,无法读取未定义的属性“ $ pristine” - Cannot read property '$pristine' of undefined when string used as input name 为什么在类方法中使用我的实例属性时未定义? - Why is my instance property undefined when used in a class method? 在jQuery事件处理程序中使用时,原型属性未定义 - Prototype property undefined when used in jquery event handler Javascript 属性在 React 中用作默认 state 时显示未定义 - Javascript property is shows undefined when used as default state in React 重构的Express中间件给出了'无法设置undefined的属性' - Refactored Express middleware gives a 'can not set property of undefined' vue.runtime.common.js:未使用this.errors时,“无法读取未定义的属性'_transitionClasses'” - vue.runtime.common.js: “Cannot read property '_transitionClasses' of undefined” when this.errors is not used 使用对象时评估对象属性 - Evaluate object property when it is used 同构样式加载器为什么引发TypeError:与CSS-Modules一起使用时,无法读取未定义的属性“ apply” - Why does isomorphic-style-loader throw a TypeError: Cannot read property 'apply' of undefined when being used in unison with CSS-Modules
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM