0

I've seen tons of javascript code use self executing functions like:

(function(){
    // ... code here
})();

But occasionally, I see people do this variant:

(function(){
    // ... code here
}).call(this);

Is there some functional difference between these 2 forms? If so, what is it?

An example of the 2nd form in the wild: https://github.com/shawnmclean/Idle.js/blob/master/build/idle.js#L160

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
goat
  • 31,486
  • 7
  • 73
  • 96

1 Answers1

2

The second form passes the value of this into the IIFE so this inside the IIFE will have the same value that it had outside the IIFE. There are many cases where this does not make a difference, but if the IIFE is inside a scope where this is set to some meaningful value, then the second form will preserve that value of this inside the IIFE.

If this in the outer scope is the global object and you are not running strict mode, then the 2nd form doesn't really change anything as this will still be the global object inside the IIFE.

But, if this is any meaningful value in strict mode or any meaningful value other than the global object when not in strict mode, then the 2nd form will extend the value of this into the enclosure.

In the example you point to, my guess is that the second form is just being used as a common design pattern, not because there really is a reason in that particular case to do it. In fact, if you look at the code example you pointed to, it doesn't even use the value of this at the top level of the IIFE so it's definitely superfluous in that specific example.

jfriend00
  • 683,504
  • 96
  • 985
  • 979