簡體   English   中英

為什么在瀏覽器中打開index.html而不是通過節點服務器提供index.html時,“ this”有何不同?

[英]Why is `this` different when opening index.html in the browser as opposed to serving index.html with a node server?

我有一個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)使thiswindow -object所有的時間,同時與服務器(網址服務index.html文件: HTTP:/ / localhost:1234 / )有時給我{} ,有時給我window

我期望testFunc()打印{} ,並且希望將window移到其他位置。 為什么不同?

注意:我使用包裹服務於我的申請。

在全局范圍內, this將始終引用全局對象。 在每個環境中,全局對象都是不同的。

有關更多信息: https : //developer.mozilla.org/en-US/docs/Glossary/Global_object

console.log("this:", this);

在全局執行上下文中, this引用全局對象。

init();

因為不是在呼叫建立和代碼是不是在嚴格模式下, 初始化函數內將引用全局對象(在嚴格模式下,它會undefined值)。

testFunc();

由於testFunc是箭頭函數,它的是從它的封閉的范圍,這是全球所以再次全局對象采納。

在瀏覽器中, window對象是全局對象的別名,並具有其他屬性(例如escapeunescape )並實現window接口。

在控制台中顯示對象時,控制台如何選擇表示對象取決於實現。

this是在當前代碼執行環境中對全局對象的引用,因此通常每次都會有所不同是正常的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM