8

在以下构造中:

(function(){

    var x = function(){
        alert('hi!');
    }

    var y = function(){
        alert("hi again!");
    }

    this.show = function(){
        alert("This is show function!");
    }

})();

为什么要this引用window对象?IIFE 中的所有内容都应该与全局范围隔离吗?xy函数也是window全局对象的属性吗?

另外,即使我var h = ...在开头使用 put :

var h = (function(){

    var x = function(){
        alert('hi!');
    }

    var y = function(){
        alert("hi again!");
    }

    this.show = function(){
        alert("This is show function!");
    }

})();

this仍然指的是窗口对象——我可以show()从全局范围内调用!怎么会?

4

2 回答 2

11

全局上下文(window在浏览器中)是在this没有其他值可使用时获得的值。

您的局部变量是局部的(即,不是 的属性window)。它们在函数内部用var.

添加var h = (function(){...没有区别的原因是因为您调用函数的方式。函数引用不是对象的属性值(如something.func()),并且您不使用.call()or调用它.apply(),因此 this 指的是全局 ( window) 对象。这就是语言被定义为起作用的方式。

于 2011-10-04T20:42:02.590 回答
10

@Pointy 是正确的,但他并没有提出整个问题 - 您可能对这个相关的答案感兴趣。这里的问题是,如果你不使用new关键字,你就没有实例化一个对象,所以没有实例this可以引用。在没有实例的情况下,this指的是window对象。

In general, you don't need this within an IIFE, because you have direct access to any function or variable defined in the anonymous function's scope - show() can call x() and y() directly, so there's no need for a this reference. There may be a valid use case for instantiating an IIFE with new, but I've never come across it.

于 2011-10-04T21:01:59.723 回答