IIFE context issues

后端 未结 2 1670
温柔的废话
温柔的废话 2020-12-06 06:54

In the following construct:

(function(){

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

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


        
相关标签:
2条回答
  • 2020-12-06 07:49

    @Pointy is correct, but he doesn't present the whole issue - you might be interested in this related answer. The issue here is that if you aren't using the new keyword, you aren't instantiating an object, so there's no instance for this to refer to. In the absence of an instance, this refers to the window object.

    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.

    0 讨论(0)
  • 2020-12-06 07:51

    The global context (window in a browser) is the value this gets when there's no other value to use.

    Your local variables are local (that is, not properties of window). They're declared inside the function with var.

    The reason why adding var h = (function(){... makes no difference is because of the way you call the function. The function reference is not a property value of an object (like something.func()), and you don't invoke it with .call() or .apply(), so therefore this refers to the global (window) object. That's just the way the language is defined to act.

    0 讨论(0)
提交回复
热议问题