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?
)};
});
};
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.
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.
forEach() executes the callbackFn function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable.
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.
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
}
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));
});
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