为了使一个 ES6 类的实例在另一个类中可用,我经常使用以下结构:
const Something=require('./something');
class AnotherClass{
makeASomething(){
var outputSomething=new Something();
return outputSomething;
}
}
module.exports=AnotherClass;
但是,我有一个类,而不是在 require()
中导入模块。在类定义之上,我将其传递到构造函数中,然后在同一个类中创建该类的实例以在 REST 端点中使用:
class AnotherClass{
constructor(Something){
this.Something=Something;
}
initialize(app){
app.post('/sendSomething',async function(req,res){
const response=new this.Something();
res.end(response.toString());
});
}
makeASomething(){
var outputSomething=new this.Something();
return outputSomething;
}
}
module.exports=AnotherClass;
我想要这样做,以便我可以进行依赖项注入(inject)并传入 Something
的版本使用模拟方法。
但是后一个版本给了我这个错误:
TypeError: Cannot read property 'Something' of undefined
所以我猜我尝试将模块传递给构造函数的方式有问题。我如何传递它以便我可以创建 Something
的实例在AnotherClass
的方法中?
编辑:添加代码以显示我如何实际创建 Something
的实例.
最佳答案
这是因为您在 app.post()
端点中使用了 function
。您需要使用箭头函数才能使 this
引用 AnotherClass
实例:
initialize(app){
app.post('/sendSomething', async (req, res) => {
const response = new this.Something();
res.end(response.toString());
});
}
关于javascript - 如果我将类的模块传递给构造函数而不是需要它,如何创建类的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60056295/