【问题标题】:How to call a function inside another function in Typescript Angular如何在 Typescript Angular 的另一个函数中调用一个函数
【发布时间】:2018-07-27 00:37:19
【问题描述】:

我是 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() {

    }
}

注意:在问这个问题之前,我在 stackoverflow 中搜索了这些链接

'this.function' is not a function - OO JS

this.function is not a function :typescript

Angular - this.function is not a function

他们说使用箭头函数来调用其他成员函数。 但我不知道如何在我的代码中实施他们的建议。可能我没有正确理解它们。

我需要你的帮助,如何使用 functionOne() 中的箭头函数调用 this.functionTwo();

感谢您的帮助。

【问题讨论】:

  • 这将 100% 正常工作,应该有比这段代码更多的东西
  • 这么多代码肯定可以工作。提供更多细节。
  • 您将函数作为回调发送.. 使用绑定。 this.marker.addListener('dragend', this.onMarkerDrop.bind(this));
  • 您好 VivekDoshi 和 Arun Raj R,感谢您的回复。我已经更新了我的代码,请检查一次。实际上在 onMarkerDrop() 上的函数中我得到了那个错误。

标签: javascript angular google-maps typescript ionic-framework


【解决方案1】:

根据您的代码更新,您可以像这样使用它:

this.marker.addListener('dragend', this.onMarkerDrop.bind(this));
// OR
this.marker.addListener('dragend', ($event) => this.onMarkerDrop($event));

您的代码将 100% 正常工作:(问题更新前)

functionOne() {
    this.functionTwo(); // Getting error this.functionTwo is not a function
}

functionTwo() {
    alert('function2');
}

请查看以下代码以获得更多说明

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');
}

为什么它可以与 fat arrow 一起使用:

这是从周围环境中提取的(词汇)。因此,您不 不再需要bind() 或that = this。

普通功能需要bind()或that = this

【讨论】:

  • 嗨@Vivek Doshi,谢谢您的回答。但我已经更新了我的问题。请检查一次。
  • @VivekDoshi 您的箭头函数示例不正确
【解决方案2】:

您的函数onMarkerDrop 作为回调传递,其中上下文将更改,this 将具有不同的值。发送时使用箭头或绑定以保留上下文。

this.marker.addListener('dragend', this.onMarkerDrop.bind(this));

或

this.marker.addListener('dragend', ($event)=>this.onMarkerDrop($event));

【讨论】:

    猜你喜欢
    • 2018-07-10
    • 2019-02-17
    • 1970-01-01
    • 2018-07-02
    • 2018-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    相关资源
    最近更新 更多