Cerulean
Cerulean

Reputation: 6013

Why does "this" inside functions defined in and passed to IIFE's reference the function itself?

Disclaimer: I've been warned that this question may be downvoted. I'd appreciate if you didn't -- I asked my teacher in a Javascript course for the explanation and he didn't know so I thought I'd ask here...

I'm trying to wrap my head around this and have been reading Kyle Simpson, but have encountered a case I don't understand.

As I understand it, when you call a function inside another function, if the function is called "standalone" (see Simpson here: You Don't Know JS: this and Object Prototypes) then this should be Window (or undefined if it in strict mode)

var fn = function globo () { console.log(this);};

function calling(called) {

console.log(called());

}
calling(fn); // "Window" or "undefined"

but if you pass a similar function to an IIFE you get a curious result

 function calling(called) {

    console.log(called());

    }(function globo () { console.log(this);}); // [Function: globo]

This seems to be a rare case where this references the function being called, instead of the "caller" or the default case of where it was defined.

Any idea what's going on here?

Upvotes: 1

Views: 61

Answers (1)

ZER0
ZER0

Reputation: 25322

Actually, that is not a IIFE. In the way you have wrote, you basically have defined a function, calling, that you never call, and after that, another function, globo, that you also never call. If you execute this code in the console, you'll get globo as result since that is the value of your last expression – since you used the parenthesis, is not a function declaration.

You can double check running this code instead:

 function calling(called) {
    console.log('foo');
 }(function globo () {});

You will have likely the same result.

A IIFE would have been:

 (function calling(called) {
    console.log(called());
 })(function globo () { console.log(this)});

Where, indeed, this returns Window (or undefined).

Upvotes: 7

Related Questions