Arrow function invocation
suggest changeIn an arrow function, this is taken from the enclosing execution context (lexical this, not the usual dynamic this). It stays that way no matter how you call the arrow function, including call, apply, and method calls. In a non-strict browser script, top-level this is window. In a module it is undefined. In Node CommonJS, top-level this is module.exports, not global.
const globalThis = this; // window in a non-strict browser script
const foo = (() => this);
console.log(foo() === globalThis); //true
const obj = { name: "Foo" };
console.log(foo.call(obj) === globalThis); //true
See how this inherits the context rather than referring to the object the method was called on.
const globalThis = this;
const obj = {
withoutArrow: function() {
return this;
},
withArrow: () => this
};
console.log(obj.withoutArrow() === obj); //true
console.log(obj.withArrow() === globalThis); //true
const fn = obj.withoutArrow; //no longer calling withoutArrow as a method
const fn2 = obj.withArrow;
console.log(fn() === globalThis); // true in a non-strict browser script
console.log(fn2() === globalThis); //true
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents