1

In JavaScript, this depends on the function call method.

  1. Calling General Functions

  2. Method Call

  3. Call constructor function

  4. arrow function call, etc.

but in this case

class Numbers {
  numberArray = [];

  multiply(arr) {
    arr.forEach(function(item) {
      this.numberArray.push(item * item);
    });
  }
}

const numbers = new Numbers();

numbers.multiply([1, 2, 3]);

If you look at the fourth line in this class example,

Since arr.forEach is calling a callback function with this, I think the arr is a this but Why does this means undefined?

I don't know why it's a general function call.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
coolhong
  • 65
  • 6
  • Well, `this` in the forEach callback has a new context, you need to pass the context of multiply to your callback. Just assign the `this` to a variable and use it in forEach callback or use the arrow function. – Hassan Imam Feb 20 '21 at 05:23
  • 1
    The `.forEach()` method is being invoked with a context of `arr`, but the callback itself isn't being called with `arr` as the context, instead, JavaScript is invoking the callback. Usually that will mean that the `this` defaults to the global object, such as the `window` in browsers. However, in "strict mode", it will default to `undefined`. Since classes run in strict-mode by default, the callback for the `forEach` will have a `this` of `undefined`. – Nick Parsons Feb 20 '21 at 05:23

0 Answers0