[英]Why is `this` different when opening index.html in the browser as opposed to serving index.html with a node server?
I have an index.html file, referencing a javascript file 我有一个index.html文件,引用了一个javascript文件
<!DOCTYPE html>
<html lang="en">
<head>
<title>asd</title>
<meta charset="utf-8">
</head>
<body>
<div id="app"></div>
<script src="index.js"></script>
</body>
</html>
In my index.js 在我的index.js中
function init() {
// always prints the window-object
console.log("init this:", this);
}
var testFunc = () => {
// this = {} when served
// this = window when opened directly in browser
console.log("testFunc this:", this);
}
// prints the window-object when opening index.html
// prints {} when using a server
console.log("this:", this);
init();
testFunc();
Why does opening the index.html file directly in the browser (url: file:///index.html) making this
the window
-object all the time, whilst serving the index.html file with a server (url: http://localhost:1234/ ) sometimes gives me {}
, and sometimes window
? 为什么直接在浏览器中打开index.html文件(:文件:URL ///index.html)使this
在window
-object所有的时间,同时与服务器(网址服务index.html文件: HTTP:/ / localhost:1234 / )有时给我{}
,有时给我window
?
I expected testFunc()
to print {}
, and I expected to get the window
elsewhere. 我期望testFunc()
打印{}
,并且希望将window
移到其他位置。 Why is it different? 为什么不同?
Note: I used parcel to serve my application. 注意:我使用包裹服务于我的申请。
this
, in the global scope, will always refer to the Global Object. 在全局范围内, this
将始终引用全局对象。 In each environment the Global Object is different. 在每个环境中,全局对象都是不同的。
For more information: https://developer.mozilla.org/en-US/docs/Glossary/Global_object 有关更多信息: https : //developer.mozilla.org/en-US/docs/Glossary/Global_object
console.log("this:", this);
this , in a global execution context, references the global object. 在全局执行上下文中, this引用全局对象。
init();
Since this is not set in the call and the code is not in strict mode, within the init function it will reference the global object (in strict mode, it would have the value undefined ). 因为这不是在呼叫建立和代码是不是在严格模式下, 初始化函数内将引用全局对象(在严格模式下,它会undefined值)。
testFunc();
Since testFunc is an arrow function, its this is adopted from its enclosing scope, which is global so again the global object. 由于testFunc是箭头函数,它的这是从它的封闭的范围,这是全球所以再次全局对象采纳。
In browsers, the window object is an alias for the global object and has additional properties (eg escape , unescape ) and implements the window interface. 在浏览器中, window对象是全局对象的别名,并具有其他属性(例如escape和unescape )并实现window接口。
How a console choses to represent an object when displaying it in the console is up to the implementation. 在控制台中显示对象时,控制台如何选择表示对象取决于实现。
this
是在当前代码执行环境中对全局对象的引用,因此通常每次都会有所不同是正常的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.