如何将上下文传递给forEach()的匿名函数

22

如何以现代且正确的方式将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?
     )};
  });

};

@GalMarrgalit - 请不要在问题编辑中添加已弃用的标签! :-) - Brian Tompsett - 汤莱恩
2个回答

34

将当前的this存储在Chart中的另一个变量中,例如:

function Chart() {
    var self = this;
    this.draw = function(data) {
        data.forEach(function(value) {
            //do something with values
            console.log(self);
        });
    }
};

此外,您可以按照以下方式传递 this,因为Array.prototype.forEach接受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
}

我更喜欢使用 self 而不是 that,因为后者对我来说太模糊了。 - RB-Develop
@RB-Develop 我的另一面是Python,所以在使用 self 的时候也感到很舒适 :) - thefourtheye
1
@MMacdonald 没什么特别的,除了Function.prototype.bind会创建一个新函数,我不认为它可以访问封闭变量(不确定,必须检查)。顺便说一下,给你点赞,这一点我一开始没有想到 :) - thefourtheye
1
@MMacdonald 好的,刚刚确认了。它甚至可以访问封闭变量。所以唯一的区别是它创建了新函数。 - thefourtheye
@thefourtheye 谢谢你提供如此详尽的答案。 - mtmacdonald
显示剩余2条评论

7

在我的答案中添加(使用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));
});

4
您漏掉了一个括号。 - Hal50000

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接