javascriptecmascript-6iifeexecutioncontext

Why is the execution context of ES6 IIFEs and ES5 IIFEs different?


The title about sums up the question - this is the code example:

!function() {
    console.log(this); // global object
}();

(function() {
    console.log(this); // global object
})();

() => {
    console.log(this); // {}
}();

var x = (function() {
    console.log(this); // global object
})();

What is happening behind the scenes wrt to the arrow function? If I wanted that scope in ES5, so far as I know, I would have to bind the execution to an empty object like so:

!function() {
    console.log(this); // global object
}.bind({})();

Solution

  • It's nothing to do with ES5 or ES6, arrow functions always get the enclosing function's context. Function invocation without using 'use strict'; is always get the global object as context (window in the browser for example), when used, the context is undefined by default.

    This is a very good article explaining the topic:

    https://dmitripavlutin.com/gentle-explanation-of-this-in-javascript/