سؤال

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