简体   繁体   English

箭头用作对象方法 - 这是未定义的而不是Window

[英]Arrow functions as a object method - this is undefined not Window

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? 我阅读了很多答案,例如: ES6对象中的方法:在本说明中使用箭头函数和说明链接github并且每个人都说应该绑定到Window,但是当我检查这些示例时,我看到undefined,如果你们中的任何一个,知道为什么?

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

I am using babel to transpile the code: 我正在使用babel来传输代码:

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

babel versions are: babel版本是:

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

but lexical this is not Window only undefined, Why ? 但词汇这不是Window唯一未定义,为什么?

It appears that you're using webpack with ES-style modules. 看来你正在使用带有ES风格模块的webpack。 Code inside modules does not have implicit access to the global scope. 模块内的代码没有对全局范围的隐式访问。 That is, this inside a module is not bound to anything. 也就是说, this一个模块内未绑定到任何东西。 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. Webpack显然用undefined替换了全局this引用,这样任何全局上下文都不会泄漏,即使它是由环境定义的。

If you try to execute console.log("this: " + (() => this)()) in the browser console, you will see that this is, indeed, window . 如果您尝试在浏览器控制台中执行console.log("this: " + (() => this)()) ,您会看到this确实是window

Well, window is not part of the javascript standard. 好吧,窗口不是javascript标准的一部分。 And since babel doesn't know the context in which your script is running it will just use undefined . 由于babel不知道脚本运行的上下文,因此只使用undefined

In nodejs for instance the global scope would be global . 例如,在nodejs中,全局范围将是global
While window is typically global scope when you are executing your code in a browser. 当您在浏览器中执行代码时, window通常是全局范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM