3

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
  • 8,458
  • 13
  • 59
  • 133

1 Answers1

6

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/

Dmitri Pavlutin
  • 18,122
  • 8
  • 37
  • 41
cstuncsik
  • 2,698
  • 2
  • 16
  • 20