Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
68
rated 0 times [  73] [ 5]  / answers: 1 / hits: 38371  / 10 Years ago, wed, april 2, 2014, 12:00:00

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?
)};
});

};

More From » foreach

 Answers
13

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
}

[#71654] Tuesday, April 1, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
davion

Total Points: 458
Total Questions: 109
Total Answers: 100

Location: Taiwan
Member since Mon, Sep 6, 2021
3 Years ago
davion questions
;