IIFE Context Issues

In the following construction:

(function(){ var x = function(){ alert('hi!'); } var y = function(){ alert("hi again!"); } this.show = function(){ alert("This is show function!"); } })(); 

Why does this refer to the window object? Should everything inside IIFE be isolated from the global realm? Are x and y also functions of the properties of the global window object?

Also, even if I use put var h = ... at the beginning:

 var h = (function(){ var x = function(){ alert('hi!'); } var y = function(){ alert("hi again!"); } this.show = function(){ alert("This is show function!"); } })(); 

this still refers to the window object - I can just call show() from the global scope! Why?

+8
source share
2 answers

The global context ( window in the browser) is the value of this when there is no other value to use.

Local variables are local (i.e., they are not window properties). They are declared inside the function using var .

The reason why adding var h = (function(){... doesn't make any difference is due to the way you call this function. The function reference is not the value of an object property (like something.func() ), and you don’t call it with .call() or .apply() , so this applies to the global ( window ) object. This is exactly how the language is defined.

+10
source

@Pointy is correct, but it does not represent the whole problem - you might be interested in this related answer . The problem here is that if you are not using the new keyword, you are not instantiating the object, so there is no instance for this for reference. In the absence of an instance, this refers to the window object.

In general, you do not need this inside IIFE because you have direct access to any function or variable defined in the scope of the anonymous function - show() can call x() and y() directly, so there is no need for this link. There may be a valid use case for an IIFE instance with new , but I never came across it.

+8
source

All Articles