【发布时间】:2019-07-24 11:49:02
【问题描述】:
我有一个 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: file:///index.html) 使 this 一直是 window 对象,同时使用 index.html 文件提供服务器(网址:http://localhost:1234/)有时给我{},有时给我window?
我希望testFunc() 打印{},我希望在其他地方得到window。为什么不一样?
注意:我使用parcel 为我的应用程序提供服务。
【问题讨论】:
标签: javascript