将this
上下文传递给匿名forEach函数的现代正确方法是什么?
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?
)};
});
};
答案 0 :(得分:24)
将当前this
存储在Chart
中的其他变量中
function Chart() {
var self = this;
this.draw = function(data) {
data.forEach(function(value) {
//do something with values
console.log(self);
});
}
};
此外,您可以像Array.prototype.forEach
接受this
this
,如下所示
arr.forEach(callback[, thisArg])
例如,
this.draw = function(data) {
data.forEach(function(value) {
//do something with values
console.log(this);
}, this); // Pass the current object as the second parameter
}
答案 1 :(得分:6)
添加我自己的答案(使用 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));
});