【问题标题】:Why is `this` different when opening index.html in the browser as opposed to serving index.html with a node server?为什么在浏览器中打开 index.html 与在节点服务器上打开 index.html 时 `this` 不同?
【发布时间】: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


    【解决方案1】:
    console.log("this:", this);
    

    this,在全局执行上下文中,引用全局对象。

    init();
    

    由于 this 没有在调用中设置并且代码不是在严格模式下,在 init 函数中它将引用全局对象(在严格模式下,它将具有值 undefined)。

    testFunc();
    

    由于 testFunc 是一个箭头函数,它的 this 是从它的封闭范围中采用的,它是全局的,所以还是全局对象。

    在浏览器中,window object 是全局对象的别名,具有附加属性(例如 escapeunescape)并实现窗口接口。

    在控制台中显示对象时,控制台如何选择表示对象取决于实现。

    【讨论】:

    • 我不知道'use strict' 做出了这样的改变。并感谢您的详尽解释
    【解决方案2】:

    this,在全局范围内,将始终引用全局对象。 在每个环境中,全局对象都是不同的。

    欲了解更多信息:https://developer.mozilla.org/en-US/docs/Glossary/Global_object

    【讨论】:

    • 感谢您的解释和链接。无论如何,我认为使用语法 var testFunc = () =&gt; { console.log(this); } 会创建 this = {},但是在浏览器中打开 index.html 时却没有,这是为什么呢?
    • 它没有给我undefined。它给了我window。直接在浏览器中打开 index.html 时,使用箭头函数和普通函数都会给我窗口对象。
    • 你说得对,我混淆了不相关的东西。您还有其他问题吗?
    【解决方案3】:

    this是对当前代码执行环境中的全局对象的引用,所以每次都不一样是正常的。

    【讨论】:

    • 这有点简单,this 可能会引用全局对象,但通常不会。
    猜你喜欢
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    • 1970-01-01
    • 2014-02-04
    • 1970-01-01
    • 2017-02-05
    相关资源
    最近更新 更多