문제

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
}

다른 팁

Adding in my own answer (use 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));
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top