问题
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?
)};
});
};
回答1:
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
}
回答2:
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));
});
来源:https://stackoverflow.com/questions/22814097/how-to-pass-context-to-foreach-anonymous-function