Home Differences between .call(this) and () on a immediately self invoking function

Differences between .call(this) and () on a immediately self invoking function

JustinJmnz
1#
JustinJmnz Published in 2017-11-14 16:08:45Z
 I came across this code in one of our online AngularJS apps, and was wondering what this does. Is it different than just calling a immediately self invoking function with parenthesis. (function() { }).call(this); // What was in TFS  vs (function() { })(); // Are these the same?  Is there any benefits of calling one over the other, or is it merely coding preference?
T.J. Crowder
2#
T.J. Crowder Reply to 2017-11-14 16:24:37Z
 They're very different. The first uses whatever the current this is (at global scope, this is a reference to the global object; in other scopes, it could be just about anything). The second will use the default this, which is a reference to the global object in loose mode but undefined in strict mode. Gratuitous example :-) : console.log("At global scope:"); (function() { console.log(this === window); // true }).call(this); // What was in TFS (function() { console.log(this === window); // true })(); (function() { "use strict"; console.log(this === window); // false (this === undefined) })(); console.log("Not at global scope:"); (function() { (function() { console.log(this === window); // false }).call(this); // What was in TFS (function() { console.log(this === window); // true })(); }).call({});// Using something other than the default .as-console-wrapper { max-height: 100% !important; }
 You need to login account before you can post.
Processed in 0.354853 second(s) , Gzip On .