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