Jav*_*SKT 5 javascript google-maps typescript ionic-framework angular
我是Angular 2的新手。我在Angular中编写了以下代码
export class TestClass {
constructor() {
this.initMap();
}
initMap() {
this.marker.addListener('dragend', this.onMarkerDrop);
}
onMarkerDrop(event) {
this.functionTwo(); // Getting error this.functionTwo is not a function
}
functionTwo() {
}
}
Run Code Online (Sandbox Code Playgroud)
注意:在问这个问题之前,我在stackoverflow中搜索了这些链接
他们说使用Arrow函数来调用其他成员函数。但是我不知道如何在我的代码中实现他们的建议。可能我对它们的理解不正确。
我想要您的帮助,如何使用functionOne();中的箭头函数调用this.functionTwo();
谢谢您的帮助。
根据您的代码更新,您可以像这样使用它:
this.marker.addListener('dragend', this.onMarkerDrop.bind(this));
// OR
this.marker.addListener('dragend', ($event) => this.onMarkerDrop($event));
Run Code Online (Sandbox Code Playgroud)
您的代码将 100% 正常工作:(更新问题之前)
functionOne() {
this.functionTwo(); // Getting error this.functionTwo is not a function
}
functionTwo() {
alert('function2');
}
Run Code Online (Sandbox Code Playgroud)
请检查以下代码以获得更多说明
functionOne() {
// this will throw error this.functionTwo is not a function
setTimeout(function(){ // normal function
this.functionTwo();
})
// This wont throw the error
setTimeout(() => { // fat arrow
this.functionTwo(); // Getting error this.functionTwo is not a function
})
}
functionTwo() {
alert('function2');
}
Run Code Online (Sandbox Code Playgroud)
为什么它会与胖箭头一起使用:
这是从周围环境(词汇)中提取的。因此,您不再需要
bind()orthat = this。使用 Normal 功能,您需要执行
bind()或that = this
您的函数onMarkerDrop作为回调传递,其中上下文将发生变化并且this将具有不同的值。发送时使用箭头或绑定来保留上下文。
this.marker.addListener('dragend', this.onMarkerDrop.bind(this));
Run Code Online (Sandbox Code Playgroud)
或者
this.marker.addListener('dragend', ($event)=>this.onMarkerDrop($event));
Run Code Online (Sandbox Code Playgroud)