1

I have a problem to understand this in Arrow functions.

I read a lot of answers for example: Methods in ES6 objects: using arrow functions and explantation in this description Link github and everyone say that this should bind to Window , but when I check these examples I see undefined, If any of you, know why?

 var foo = {
     bar: () => console.log(this)  // lexical this is window or something else
 }
 foo.bar()

I am using babel to transpile the code:

var foo = {
        bar: function bar() {
            return console.log(undefined);
        }
}

babel versions are:

  • "babel-core": "^6.21.0",
  • "babel-loader": "^6.2.10",
  • "babel-preset-es2015": "^6.18.0",
  • "babel-preset-stage-2": "^6.18.0",

but lexical this is not Window only undefined, Why ?

Community
  • 1
  • 1
Agata
  • 504
  • 9
  • 18

2 Answers2

3

It appears that you're using webpack with ES-style modules. Code inside modules does not have implicit access to the global scope. That is, this inside a module is not bound to anything. Webpack apparently replaces global this references with undefined so that any global context does not leak in even if it's defined by the environment.

If you try to execute console.log("this: " + (() => this)()) in the browser console, you will see that this is, indeed, window.

Stefan Dragnev
  • 12,268
  • 6
  • 44
  • 50
  • You can pass `{modules: false}` as your options to `babel-preset-es2015` to stop module processing, if you want. – loganfsmyth Jan 18 '17 at 17:44
  • I wonder what that would result in. I mean babel can't really know if it will be executed in a browser or another environment, right? – Forivin Jan 18 '17 at 19:02
1

Well, window is not part of the javascript standard. And since babel doesn't know the context in which your script is running it will just use undefined.

In nodejs for instance the global scope would be global.
While window is typically global scope when you are executing your code in a browser.

Forivin
  • 12,200
  • 21
  • 77
  • 171