Javascript 如何将上下文传递给forEach()匿名函数
将Javascript 如何将上下文传递给forEach()匿名函数,javascript,foreach,this,Javascript,Foreach,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? )}; }); };
此
上下文传递给匿名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?
)};
});
};
将当前
this
存储在图表中的其他变量中,如下所示
function Chart() {
var self = this;
this.draw = function(data) {
data.forEach(function(value) {
//do something with values
console.log(self);
});
}
};
此外,您还可以像下面一样传递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
}
添加我自己的答案(使用bind):
我更喜欢使用self
而不是that
,这对我来说太模棱两可了。哈哈,不错的一个:)不过这几天似乎一直是我个人的偏好。所以这真的取决于你觉得什么是适合使用的。@RB develope我的另一面是Python,所以我对self
:)@mmacdonal也不太熟悉,只不过这会创建一个新函数,我认为它不能访问包含的变量(对此不确定,必须检查)。顺便说一句,对你来说+1,我一开始没想到:)@MMacdonald好的,刚刚确认。它甚至可以访问封闭的变量。所以,唯一的区别是,它创建了新的函数somewhere@GalMarrgalit-请不要在编辑问题时添加不推荐的标记!:-)
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));
});