【发布时间】:2017-01-31 03:10:56
【问题描述】:
我有一个函数,叫它meow(),作为类的一部分,叫它Cat:
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
【问题讨论】:
标签: javascript typescript this