I'm trying to call a function from a 5-deep nested function in Typescript, and it's not able to see the outside function. Running console.log(this)
inside of setTimeout returns the window
object.
export class SearchComponent implements OnInit {
lifeCycleFunc(){ //Function 1
...
if() { //Function 2
....
var.do(item => { //Function 3
....
var.forEach(var => { //Function 4
...
setTimeout(function(){ //Function 5
this.searchFunc() //this.searchForAssignments is not a function
}
})
})
}
}
searchFunc(){
...
}
}
this
context inside setTimeout
callback is going to be global object (window
), but it should be SearchComponent
class for this code to work correctly. To achieve that all nested functions including setTimeout
callback should be arrow functions to bind this
context correctly:
export class SearchComponent implements OnInit {
lifeCycleFunc(){
...
if(condition) {
...
foo.do(bar => {
...
bar.forEach(baz => {
...
setTimeout(() => {
this.searchFunc();
}, 0);
});
});
}
}
searchFunc(){
...
}
}
To answer your question and your comment about making it an arrow function, you do this:
setTimeout(() => {
this.searchFunc();
}, 0);
instead of:
setTimeout(function() {
this.searchFunc();
}, 0);
var.forEach(var => { //Function 3
...
this.searchFunc() //TypeError: this.searchForAssignments is not a function
}.bind(this))
The this
reference inside the forEach
is the forEach function. You need to bind it to the this reference of the class.