Arrow functions as a object method

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 ?


    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 .


    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.

    链接地址: http://www.djcxy.com/p/32954.html

    上一篇: 解决模块尚未加载,但错误Babel异步

    下一篇: 箭头用作对象方法