0

I have some code here. I am aware that this reference wont be carried in anonymous functions. But here, even when using a function of an object, the this inside that is window.

var MyClass = function (div) {

    this.array = [];
};

MyClass.prototype = {
  addToArray: function (elem) {
    this.array.push(elem);
  },
  processAndAdd: function(elemArray){
    elemArray.forEach(this.addToArray);
  }
}

var myObj = new MyClass();
myObj.processAndAdd([1, 2, 3]);
console.log('test');

Error: Line: this.array.push(elem);

push of undefined.

On inspection, the this here is window Object

I want to know why this is window here, and how to restructure my code to properly handle this.

Caleb Hillary
  • 525
  • 6
  • 10
  • 2
    When you pass the function reference to `forEach`, it loses its `this`, as it's no longer being called on the `this` (ie: myObj). The `.forEach()` method allows you to specify the this for the callback: `.forEach(this.addToArray, this)` – Nick Parsons Apr 21 '21 at 11:55

1 Answers1

0

The reference to this object is no more MyClass constructor after you pass the callback function body as callback to forEach. Bind the function body with the current this context and your code should work.

    var MyClass = function (div) {
    
        this.array = [];
    };
    
    MyClass.prototype = {
      addToArray: function (elem) {
        this.array.push(elem);
      },
      processAndAdd: function(elemArray){
        elemArray.forEach(this.addToArray.bind(this));
      }
    }
    
    var myObj = new MyClass();
    myObj.processAndAdd([1, 2, 3]);
    console.log('test');
  • The issue with bind is that it will create a new function right? This part of the code will be called many times, and I want it to be as effecient as possible. I think that Nick's comment might be a better suit for me. I can pass the context to foreach. – Caleb Hillary Apr 21 '21 at 12:41