2017-10-17 47 views
0

如何在打字稿中從單獨的嵌入式函數內擊中某個函數?嵌套方法中的命中方法

我試圖完成什麼...在僞;

export class blah { 

    functionOne(result) { 
     // do stuff with the result of functionTwoChildMethod... 
    }; 

    const geocoder = new google.maps.Geocoder(); 

    geocoder.geocode (paramObj, function (res, stat) { 

     functionTwoChildMethod =() => { 
     this.functionOne(result); 
     }; 

    }; 
}; 

似乎做this.functionOne(result);沒有達到類範圍的母體火過functionOne什麼的。那麼我錯過了什麼?感謝您的任何方向這已經困擾了我的時間比我願意分享:)

回答

0

this將是瘋狂的,我知道,但嘗試that;)

export class blah { 

    functionOne(result) { 
     // do stuff with the result of functionTwoChildMethod... 
    }; 

    const geocoder = new google.maps.Geocoder(); 
    var that = this; 
    geocoder.geocode (paramObj, function (res, stat) { 

     functionTwoChildMethod =() => { 
     that.functionOne(result); 
     }; 

    }; 
}; 

this您使用的是一個範圍在哪裏沒有你需要的功能內,但通過將其分配給that你能給我們您需要的功能;) 這是所有變量的作用域

+0

HA!是的......那不是我會猜到的邏輯!非常感謝!如果我也可以upvote,但我會,但我的代表太低了,但你要麼我的感謝! :) – LearningNewStuff

+0

別擔心,我只是高興地幫助:) –

0

So what am I missing

this

修復

使用箭頭功能

export class blah { 

    functionOne(result) { 
     // do stuff with the result of functionTwoChildMethod... 
    }; 

    const geocoder = new google.maps.Geocoder(); 

    geocoder.geocode (paramObj, (res, stat) => { // Use arrow here 

     functionTwoChildMethod =() => { 
     this.functionOne(result); 
     }; 

    }; 
}; 

更多

https://basarat.gitbooks.io/typescript/docs/arrow-functions.html

+0

我得到的未捕獲TypeError:_this.functionOne不是函數 錯誤,似乎仍然沒有找到它? – LearningNewStuff

+0

@LearningNewStuff然後你有更多的錯誤。我已經用箭頭更新了答案 – basarat

+0

對不起,沒有運氣,也許我的例子有點含糊,是否會影響functionTwo是一個來自const對象的匿名函數?請參閱我更新的問題示例以瞭解更多具體信息,我正嘗試從新的Google實例匿名函數之外獲取信息,以便將API結果報告給其他方法。 – LearningNewStuff