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

时间:2014-04-02 14:07:50

标签: javascript foreach this

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?
     )};
  });

};

2 个答案:

答案 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));
});