'this' undefined inside foreach loop

I am writing typescript code and iterating an array. Inside the loop, I am trying to access the 'this' object to do some processing like:

console.log('before iterate, this = ' +this); myarray.days.forEach(function(obj, index) { console.log('before transform, this : ' + this); this.datePipe.transform... }); 

but this fails because he complains that 'this' is undefined. The 'this' object correctly prints as [object's object] before / outside the loop, but inside the loop it is undefined. Why is this? And what is this correction for?

+15
source share
3 answers

You need to either use the function:

 myarray.days.forEach((obj, index) => { console.log('before transform, this : ' + this); this.datePipe.transform... }); 

Or use the binding method :

 myarray.days.forEach(function(obj, index) { console.log('before transform, this : ' + this); this.datePipe.transform... }.bind(this)); 

The reason is that when passing a regular function as a callback when it is called, this is not actually saved.
The two methods that I mentioned above will ensure that the scope of this right is preserved for future execution of the function.

+41
source

Add this as a parameter to the callback.

Addition }, this); instead of }.bind(this)); should solve the problem in Angular.

So it should look like this:

 myarray.days.forEach(function(obj, index) { console.log('before transform, this : ' + this); this.datePipe.transform... }, this); 
+4
source

Try it:

 myarray.days.forEach( (obj) => { console.log('before transform, this : ' + this); this.datePipe.transform... }); 
0
source

Source: https://habr.com/ru/post/1267363/


All Articles