为了使一个ES6类的实例在另一个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;
我想这样做,以便可以进行依赖项注入并使用模拟方法传递Something
版本。
但是后一个版本给我这个错误:
TypeError: Cannot read property 'Something' of undefined
因此,我想将模块传递给构造函数的方式有问题。如何传递它,以便可以在Something
的方法中创建AnotherClass
的实例?
编辑:添加了代码,以显示我实际上如何创建Something
的实例。
这是因为您在function
端点中使用了app.post()
。您需要使用箭头功能才能使this
引用AnotherClass
实例:
initialize(app){
app.post('/sendSomething', async (req, res) => {
const response = new this.Something();
res.end(response.toString());
});
}
您遇到范围问题。发布功能中的this
未引用AnotherClass
。您可以通过在调用post函数之前将值存储在变量中来解决此问题:
class AnotherClass{
constructor(Something){
this.Something=Something;
}
initialize(app){
const _something = this.Something;
app.post('/sendSomething',async function(req,res){
const response=new _something();
res.end(response.toString());
});
}
makeASomething(){
var outputSomething=new this.Something();
return outputSomething;
}
}
module.exports=AnotherClass;