[英]console.log(this) in global scope returns undefined
I have created a script which logs the this variable to the console in the global scope.我创建了一个脚本,将 this 变量记录到全局范围内的控制台。 If I launch the script in the browser it returns undefined.如果我在浏览器中启动脚本,它会返回未定义。 eg.例如。
console.log(this); //returns undefined
However if I enter the same command directly in the browser console it returns the window object.但是,如果我直接在浏览器控制台中输入相同的命令,它会返回窗口对象。 Which is what I was expecting.这是我所期待的。 eg.例如。
console.log(this); //returns Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}
Why is the behavior/output of logging 'this' to the console different in the browser console and different while inspecting the output from a script?为什么在浏览器控制台中将“this”记录到控制台的行为/输出与检查脚本输出时不同?
Edit: I am compiling the script with babel (es2015 preset).编辑:我正在用 babel(es2015 预设)编译脚本。 As far as my initial question is concerned the issue is now resolved.就我最初的问题而言,问题现在已经解决。 Disabling the Babel preset/plugins results in the expected output of the this variable.禁用 Babel 预设/插件会导致 this 变量的预期输出。
此外,如果您使用的是 ES6 模块,则会自动启用严格模式,如果在全局范围内使用它,它将返回 undefined。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.