为什么`this`是这个JavaScript中的Window对象?

ben*_*e89 1 javascript

在这里有一个完整的噩梦,努力向自己解释为什么thiswindow对象?

(function () {

    function get () {
        alert(this);
    }

    get();

})();
Run Code Online (Sandbox Code Playgroud)

我的理解是函数在JS中创建了范围,它是如何引用windowObject的?

mea*_*gar 7

因为这是JavaScript的工作方式,禁止严格模式.

thiswindow,除非你明确地调用一个方法不同的对象上.您发布的代码get没有显式调用this,因此调用它window.

x.method() // "this" will be "x"

method() // "this" will be "window"
Run Code Online (Sandbox Code Playgroud)

  • 在严格模式下不是这种情况.`(function(){"use strict"; this.x = 5;})(); // TypeError` - 应该首选严格模式的众多原因之一. (2认同)