Arrow function invocation

suggest change

In 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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents