'this' is undefined inside the foreach loop

31,389

Solution 1

You need to either use an arrow function:

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

Or use the bind 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 invoked the this is not actually preserved.
The two ways which I mentioned above will make sure that the right this scope is preserved for the future execution of the function.

Solution 2

Add the this as a parameter for callback.

Adding }, this); instead of }.bind(this)); should resolved issue in Angular.

Thus, should look like:

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

Solution 3

Try this:

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

Related videos on Youtube

user1892775
Author by

user1892775

Updated on April 23, 2020

Comments

  • user1892775
    user1892775 about 4 years

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

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

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

  • Ziggler
    Ziggler about 2 years
    Sometimes SO frustrates me and most of the times it helps in my problems as this..
  • Ziggler
    Ziggler about 2 years
    Nice explanation..