Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass context to forEach() anonymous function [duplicate]

What's the modern and correct way to pass the this context to an anonymous forEach function?

function Chart() {

  this.draw = function(data) {
     data.forEach(function(value) {
       //do something with values
       console.log(this); //question: how to get Chart instead of global scope?
     )};
  });

};
like image 324
mtmacdonald Avatar asked Apr 02 '14 14:04

mtmacdonald


People also ask

Does forEach return promise?

JavaScript Promises forEach with promises It is possible to effectively apply a function ( cb ) which returns a promise to each element of an array, with each element waiting to be processed until the previous element is processed.

What is an alternative to forEach?

The every() function is a good alternative to forEach, let us see an example with a test implementation, and then let's return out of the every() function when a certain condition meet.

Can forEach return a value?

forEach() executes the callbackFn function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable.

How does forEach work JavaScript?

The forEach() method executes a function once for each item in the array. The method is called on the array object that you wish to manipulate, and the function to call is provided as an argument. In the code above, console. log() is invoked for each element in the array.


2 Answers

Store the current this in some other variable in Chart like this

function Chart() {
    var self = this;
    this.draw = function(data) {
        data.forEach(function(value) {
            //do something with values
            console.log(self);
        });
    }
};

Also, you can pass the this like the following, as Array.prototype.forEach accepts this

arr.forEach(callback[, thisArg])

For example,

this.draw = function(data) {
    data.forEach(function(value) {
        //do something with values
        console.log(this);
    }, this); // Pass the current object as the second parameter
}
like image 67
thefourtheye Avatar answered Oct 04 '22 08:10

thefourtheye


Adding in my own answer (use bind):

this.draw = function(data) {
   data.forEach(function(value) {
     //do something with values
     console.log(this); //question: how to get Chart instead of global scope?
   }.bind(this));
});
like image 36
mtmacdonald Avatar answered Oct 04 '22 09:10

mtmacdonald