这个里面的 iife 指向 window?

this inside iife points to window?

了解 JavaScript。我对这个 inside iife 的范围感到困惑。为什么 this 指向 iife 中的 window 对象?这应该指向 myObj,因为它在 myObj 中。

window.foo = "bar1";
var myObj = {
   foo: "bar2",
   func: function() {
       var self = this;
       console.log(this.foo + ", " + self.foo);
       (function xx() {
           console.log(this.foo + ", " + self.foo)
       }());
   }
}
myObj.func();

输出 -

bar2, bar2
bar1, bar2

我担心第二行的 bar1。

函数xx被称为IIFE,这是一个简单的函数调用。根据规范,在简单的函数调用中,全局对象(浏览器中的 window)被分配给 this.

window.foo = "bar1";
var myObj = {
   foo: "bar2",
   func: function() {
       var self = this;
       console.log(this.foo + ", " + self.foo);
       (function xx() {
           console.log(`this === window :`, this === window);
           console.log(this.foo + ", " + self.foo)
       }());
   }
}
myObj.func();

参考:

Since the following code is not in strict mode, and because the value of this is not set by the call, this will default to the global object, which is window in a browser.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this