如何将上下文传递给forEach()匿名函数 [英] How to pass context to forEach() anonymous function
本文介绍了如何将上下文传递给forEach()匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个上下文传递给一个匿名forEach函数的现代正确的方法是什么? > function Chart(){
this.draw = function(data){
data.forEach(function(value){
// do something值
console.log(this); //问题:如何得到Chart而不是全局作用域?
)};
});
};
解决方案
将当前 / code>在
Chart
中的其他变量中,像这样
function Chart(){
var self = this;
this.draw = function(data){
data.forEach(function(value){
//做一些值
console.log(self);
});
}
};
另外,您可以将这个
以下是 Array.prototype.forEach
接受这个
arr .forEach(callback [,thisArg])
例如,
this.draw = function(data){
data.forEach(function(value){
//用值
console.log(this);
},this); //传递当前对象作为第二个参数
code $ pre
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?
)};
});
};
解决方案 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
}
这篇关于如何将上下文传递给forEach()匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文