Búsqueda de sitios web

javascript - Cómo llamar a una función dentro de otra función en Typescript Angular


Soy nuevo en Angular 2. Escribí el siguiente código en 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() {

    }
}

Nota: Antes de hacer esta pregunta, busqué en Stack Overflow y obtuve estos enlaces

'this.function' no es una función - JS OO

this.function no es una función :typescript

Angular - this.function no es una función

Ellos están diciendo que use funciones Arrow para llamar a otras funciones miembro. Pero no sé cómo implementar sus sugerencias en mi código. Tal vez no los entendí correctamente.

Quiero ayuda de ti sobre cómo llamar a this.functionTwo() usando una función flecha desde functionOne();

Gracias por tu ayuda.

Respuesta #1

Según la actualización de su código, puede usarlo así :

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

Tu código funcionará perfectamente al 100% : (Antes de que se actualizara la pregunta)

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

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

Por favor, revise el código siguiente para más aclaración

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

Por qué funcionará con fat arrow :

esto se recoge del entorno (lexical). Por lo tanto, ya no necesitas bind() o that=this.

Con la función normal necesitas hacer bind() o that=this

Respuesta #2

Tu función onMarkerDrop se pasa como un callback donde el contexto cambiará y this tendrá un valor diferente. Usa arrow o bind al enviarla para preservar el contexto.

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

o

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

Artículos relacionados