Подтвердить что ты не робот

Как передать контекст анонимной функции 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?
     )};
  });

};
4b9b3361

Ответ 1

Сохраняйте текущий 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
}

Ответ 2

Добавление в мой собственный ответ (используйте 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)};
});