IIFE context issues
Asked Answered
L

2

8

In the following construct:

(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 window object? Should everything inside IIFE be isolated from global scope? Are x and y functions also properties of window global 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 window object -- I can just call show() from the global scope! How come?

Libertarian answered 4/10, 2011 at 20:39 Comment(0)
S
11

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.

Stodgy answered 4/10, 2011 at 20:42 Comment(0)
K
10

@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.

Kith answered 4/10, 2011 at 21:1 Comment(2)
A valid case would be when you need to pass "this" within an IIFE to another object that uses it to make callbacks.Zimbabwe
@AndroidDev, you could use local object and treat it as 'this', pass it to another object when that should access your 'this' as it's 'this' with bind() methodCreamcups

© 2022 - 2024 — McMap. All rights reserved.