Why does Promise.then
passes execution context of undefined
when using a class method as callback, and window
when using a "normal function"?
Is the class method detached from its owning object/class? and why undefined
and not window
?
function normal() {
console.log('normal function', this);
}
const arrow = () => {
console.log('arrow function', this);
}
function strictFunction() {
'use strict';
console.log('strict function', this);
}
class Foo {
test() {
this.method(); // Foo
Promise.resolve().then(() => console.log('inline arrow function', this)); // Foo
Promise.resolve().then(normal); // window
Promise.resolve().then(arrow); // window
Promise.resolve().then(strictFunction); // undefined
Promise.resolve().then(this.method); // undefined <-- why?
}
method() {
console.log('method', this);
}
}
const F = new Foo();
F.test();
(jsFiddle)
I would expect the context of this.method
to be lost but cannot understand why the different behavior between this.method
and "normal" and arrow functions.
Is there a spec for this behavior? The only reference I found was Promises A+ refering to that "in strict mode this
will be undefined
inside; in sloppy mode, it will be the global object
.".