I am new to Angular 2. I wrote below code in 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() {
}
}
Note: Before asking this question I searched in stackoverflow I got these links
'this.function' is not a function - OO JS
this.function is not a function :typescript
Angular - this.function is not a function
They are saying that use Arrow functions to call other member functions. But I don't know how to implement their suggestions in my code. Might I didn't understood them correctly.
I want help from you like, how to call this.functionTwo() using arrow function from functionOne();
Thank you for your help.
To call a function inside another function, define the inner function inside the outer function and invoke it. When using the function keyword, the function gets hoisted to the top of the scope and can be called from anywhere inside of the outer function.
Recursion. You can call the same function from within itself in TypeScript. This is called recursion. All recursive functions must have an end condition, which is called the base case, so that it knows when it stops executing.
It is important to understand that each of the functions we write can be used and called from other functions we write. This is one of the most important ways that computer scientists take a large problem and break it down into a group of smaller problems.
As per your code updation , you can use it like :
this.marker.addListener('dragend', this.onMarkerDrop.bind(this));
// OR
this.marker.addListener('dragend', ($event) => this.onMarkerDrop($event));
Your code will work 100% fine : (Before Question Updated)
functionOne() {
this.functionTwo(); // Getting error this.functionTwo is not a function
}
functionTwo() {
alert('function2');
}
Please check the below code for more clarification
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');
}
Why it will work with fat arrow :
this is picked up from surroundings (lexical). Therefore, you don’t need
bind()
orthat = this
, anymore.With Normal function you need to do
bind()
orthat = this
Your function onMarkerDrop
is passed as a callback where the context will change and this
will have a different value. Use arrow or bind while sending to preserve context.
this.marker.addListener('dragend', this.onMarkerDrop.bind(this));
or
this.marker.addListener('dragend', ($event)=>this.onMarkerDrop($event));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With