我有一个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>在我的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();为什么直接在浏览器中打开index.html文件(url: index.html使this成为window-object,而使用服务器(url:http://localhost:1234/)为index.html文件提供服务时,有时会给我{},有时给出window
我希望testFunc()能打印{},我也希望能在其他地方得到window。为什么不一样?
注意:我使用包裹来服务我的应用程序。
发布于 2019-07-24 12:13:29
console.log("this:", this);这在全局执行上下文中引用全局对象。
init();由于这不是在调用中设置的,而且代码也不是处于严格模式中,因此在init函数中它将引用全局对象(在严格模式下,它将具有未定义的值)。
testFunc();因为testFunc是一个箭头函数,它的这个函数是从它的封闭作用域(也就是全局对象)中采用的。
在浏览器中,对象是全局对象的别名,具有附加属性(例如,转义、取消转义)并实现窗口接口。
控制台在控制台中显示对象时如何选择表示对象取决于实现。
发布于 2019-07-24 11:53:38
在全局范围内,this将始终引用全局对象。在每个环境中,全局对象是不同的。
有关更多信息:对象
发布于 2019-07-24 11:53:58
this是对当前代码执行环境中的全局对象的引用,所以每次都会不同是正常的。
https://stackoverflow.com/questions/57182213
复制相似问题