Skip to content Skip to sidebar Skip to footer

Arrow Functions Return This As The Window Object

In my program using the function() syntax is returning the this value of a target element, but using an arrow function returns the window object. How are each of these two function

Solution 1:

That is perfectly normal & expected behaviour of arrow functions.

As the documentation mentions about regular functions:

every new function defined its own this value (a new object in the case of a constructor, undefined in strict mode function calls, the context object if the function is called as an "object method", etc.).

If it is required to override the value of this in a regular function, then instead of calling it directly, we can invoke it using call() or apply().

So in your case of regular function, the callback function is getting invoked internally by addEventListener function using a call() or apply() with value of this set to element bound to clocksTemplate.gmt. It's a standard practice to use call() or apply() for invoking callbacks.

In case of the first function (arrow function), the this does not get assigned any new value. They can't be invoked using call() or apply() because arrow functions are anonymous. So it continues to have the value that was defined by the enclosing function editTemplates() and that happens to be window.

See below for code example:

// REGULAR FUNCTION

function editTemplates() {

    console.log(this)    // window
    var myVar = this;

    // sits within for loop

    clocksTemplate.gmt[i].addEventListener('keydown', function(e) {

        // new value assigned for 'this' as element bound to clocksTemplate.gmt

        console.log(this);    // returns element bound to clocksTemplate.gmt

        console.log(myVar);    // returns window
    });



// ARROW FUNCTION (Anonymous Functions)

function editTemplates() {

    console.log(this)    // returns window object
    var myVar = this;

    // sits within for loop

    clocksTemplate.gmt[i].addEventListener('keydown', (e) => {

        // No new value gets assigned to 'this'

        console.log(this); // returns window object

        console.log(myVar);    // returns window object

        // Saves the hassle of saving 'this' to another variable!
    });

Hope this answers your question.


Post a Comment for "Arrow Functions Return This As The Window Object"