1

Why does the following snippet return true and undefined?

var fns = {
  foo() {
    console.log(this === window); // true (instead of false)
    console.log(typeof this.bar); // undefined (instead of function)
  },
  bar() {},
};

Promise.resolve().then(fns.foo);

(If I run fns.foo(); instead of Promise.resolve().then(fns.foo); it prints false and function as expected)

Is it a promise specific definition?

I checked

Xaver Fleer
  • 99
  • 1
  • 8
  • It isn't *bound* that's the issue. The value of `this` is determined *at the time of calling the function*. When we talk about "bound context" then it's determined once and calling the function will not change it. – VLAZ May 27 '20 at 20:29
  • Also relevant: [How to access the correct `this` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – VLAZ May 27 '20 at 20:30
  • Related to the issue though; `Promise.resolve().then(_ => fns.foo());` – Taplar May 27 '20 at 20:30
  • 1
    The value of this is less complicated than it looks. In general you just have to ask one question: Who is the caller? In fns.foo() the caller is fns. In ..then(fns.foo), the caller is not fns. Then that's when things may become a bit more complicated, whether you are in strict mode or not, or if the function has already a value of this bound to it. – Kev May 27 '20 at 20:36
  • "In ..then(fns.foo), the caller is not fns" – Xaver Fleer May 27 '20 at 20:53

0 Answers0