2
我有一个函数,调用它meow()
,作为一类的一部分,称之为Cat
:如何在传递函数时保持'this'的原始范围?
export class Cat(){
private meow(){
console.log(this);
}
现在,说我有另一个类,称之为Kitten
,这需要一个函数作为其构造的一部分:
export class Kitten {
var kittenMeow: {(): void; }; //note the typing
constructor(functionForMeow : {(): void; }){ //note the typing
this.kittenMeow = functionForMeow;
}
public meow(){
this.kittenMeow();
}
}
现在说我添加以下到Cat
类:
export class Cat(){
constructor(){
this.giveBirth();
}
private meow(){
console.log(this);
}
giveBirth(){
var kitty = new Kitten(this.meow);
kitty.meow();
}
}
当我运行此代码时,“Kitten”被记录到控制台。我怎样才能让“猫”登录到控制台?也就是说,我怎么保存的this
原来的范围,使this
指Cat
而不是Kitten
我还想补充一点,TypeScripts'胖箭头'不会捕获'this',你可以用'this'注释回调类型来显式地要求这是一个特定的类型。参考:https://www.typescriptlang.org/docs/handbook/functions.html#this – shusson