unrest7972
unrest7972

Reputation: 1

In some cases, "this" in the function passed as an argument to the higher order function is Window or undefined. Please tell me the difference

class Foo {
  
  m(f) {
    f();
  }
}
let foo = new Foo();


foo.m(function () {
  console.log(this);
  // Window
});
class Foo {
  
  m(f) {
    f();
  }
}

class Boo {
 
  m2() {
    let foo = new Foo();

    foo.m(function () {
      console.log(this);
      // undefined
    });
  }
}
let boo = new Boo();
boo.m2();

Why are the two results different?

I think this should be undefined in both because they are called in a function format rather than an object calling them in a method format like o.method(). If Window is calling it implicitly, why is the second code undefined?

I looked up lexical context and execution, but it was too difficult to understand.

In the case of arrow functions, it was possible to predict what "this" would be, but in the case of anonymous functions, it was not possible to predict.

Upvotes: 0

Views: 33

Answers (0)

Related Questions