2

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({})();
Zach Smith
  • 7,693
  • 10
  • 49
  • 111

1 Answers1

5

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://rainsoft.io/gentle-explanation-of-this-in-javascript/

cstuncsik
  • 2,519
  • 2
  • 15
  • 19