JavaScript Scope Arrow function invocation



When using arrow functions this takes the value from the enclosing execution context's this (that is, this in arrow functions has lexical scope rather than the usual dynamic scope). In global code (code that doesn't belong to any function) it would be the global object. And it keeps that way, even if you invoke the function declared with the arrow notation from any of the others methods here described.

var globalThis = this; //"window" in a browser, or "global" in Node.js

var foo = (() => this);           

console.log(foo() === globalThis);          //true

var obj = { name: "Foo" };
console.log( === globalThis);  //true

See how this inherits the context rather than referring to the object the method was called on.

var globalThis = this;

var obj = {
    withoutArrow: function() {
        return this;
    withArrow: () => this

console.log(obj.withoutArrow() === obj);      //true
console.log(obj.withArrow() === globalThis);  //true

var fn = obj.withoutArrow; //no longer calling withoutArrow as a method
var fn2 = obj.withArrow;
console.log(fn() === globalThis);             //true
console.log(fn2() === globalThis);            //true