当 Inject-able class 的函数作为参数发送到另一个模块时,"this" 未定义
"this" is undefined when function of an Inject-able class is sent as argument to another module
这就是我想要做的,我将函数引用从 Provider1(存在于模块 1 中)传递给 Provider2(存在于模块 2 中)。当我尝试调用该函数时,“this”的值未定义。知道可能出了什么问题吗?
Module1.ts
@Module({
controllers: [Controller1],
providers: [Provider1],
})
export class Module1{}
Provider1.ts
@Injectable()
export class Provider1 {
constructor(private readonly provider2: Provider2) {}
providerFunction() {
this.provider2.provider2Function(new HelperClass().helperFunction);
}
}
HelperClass.ts
@Injectable()
export class HelperClass {
helperFunction() {
return this.someValue; //Here, this is undefined
}
}
Provider2.ts
@Injectable()
export class Provider2 {
provider2Function(helperFunction: ()=>void) {
console.log(helperFunction());
}
}
这是因为 this
以这种方式传递方法时发生了变化。像这样尝试:
@Injectable()
export class Provider1 {
constructor(private readonly provider2: Provider2) {}
providerFunction() {
const helper = new HelperClass();
this.provider2.provider2Function(helper.helperFunction.bind(helper));
}
}
详细了解 this
关键字的工作原理 here。
这就是我想要做的,我将函数引用从 Provider1(存在于模块 1 中)传递给 Provider2(存在于模块 2 中)。当我尝试调用该函数时,“this”的值未定义。知道可能出了什么问题吗?
Module1.ts
@Module({
controllers: [Controller1],
providers: [Provider1],
})
export class Module1{}
Provider1.ts
@Injectable()
export class Provider1 {
constructor(private readonly provider2: Provider2) {}
providerFunction() {
this.provider2.provider2Function(new HelperClass().helperFunction);
}
}
HelperClass.ts
@Injectable()
export class HelperClass {
helperFunction() {
return this.someValue; //Here, this is undefined
}
}
Provider2.ts
@Injectable()
export class Provider2 {
provider2Function(helperFunction: ()=>void) {
console.log(helperFunction());
}
}
这是因为 this
以这种方式传递方法时发生了变化。像这样尝试:
@Injectable()
export class Provider1 {
constructor(private readonly provider2: Provider2) {}
providerFunction() {
const helper = new HelperClass();
this.provider2.provider2Function(helper.helperFunction.bind(helper));
}
}
详细了解 this
关键字的工作原理 here。