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

mtm*_*ald 14 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?
     )};
  });

};
Run Code Online (Sandbox Code Playgroud)

the*_*eye 27

将电流存储this在其他变量中,Chart如下所示

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

此外,您可以传递this以下内容,作为Array.prototype.forEach接受this

arr.forEach(callback[, thisArg])
Run Code Online (Sandbox Code Playgroud)

例如,

this.draw = function(data) {
    data.forEach(function(value) {
        //do something with values
        console.log(this);
    }, this); // Pass the current object as the second parameter
}
Run Code Online (Sandbox Code Playgroud)


mtm*_*ald 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));
});
Run Code Online (Sandbox Code Playgroud)

  • 你错过了某个地方的parens (4认同)