My html file named index.html is referencing a javascript file
<!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>
The contents of my 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();
I am puzzled by the fact that when I open the index.html file directly in the browser (url: file:///index.html), it always sets this
to be the window
-object, but when I serve the index.html file with a server (url: http://localhost:1234/), sometimes {}
is printed and other times window
.
I initially anticipated getting {}
when executing testFunc()
, and having window
as the output in all other cases. Why is there such inconsistency?
Just for reference: I utilized parcel to serve my application.