Arrow functions return this as the window object

折月煮酒 提交于 2019-12-01 13:36:27

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!