4 ms·
Immediately invoked function expression - aka an anonymous function that executes as it is interpreted. (function() { console.log('test'); })(); In old ve
by CryoLogic 7y ago
Immediately invoked function expression - aka an anonymous function that executes as it is interpreted.
(function() { console.log('test'); })();
In old versions of JavaScript, variables had to be scoped to the nearest function (rather than the nearest block) so IIFE where often used for namespacing:
var $ = (function() { this.version = '1.2.3'; })();
$.version; // 1.2.3
This worked because the function would be immediately invoked upon interpretation, scoping it's contents to itself (aliased by the variable name).
- furgooswft13 7y agoHate to be a wet blanket, but that second code sample won't work. The function doesn't return anything so $ === undefined. Even if it did, this in that context is bound to the global object, so is the same as setting a variable without var or let. A proper example of IIFE for lexical scoping would be something like this: var numbers = ""; (function(){ for (var i=0; i<5; i++) { numbers += i + " "; } })(); console.log(i) //undefined Nowadays of course you could just use let instead of var Your code snippet would kind of work as expected if used as a constructor. As in: var $ = function() { this.version = '1.2.3'; }; var obj = new $; console.log(obj.version); //1.2.3 Of course that is not a IIFE. Ah...brings me back to my SO days...
- momokoko 7y agoHate to dry off the blanket but they just forgot the `new` keyword for `this` ;) var $ = new (function() { this.version = '1.2.3'; })(); console.log($.version); // '1.2.3' EDIT: Or if you really want to abuse the spec var $ = (function() { if (!(this instanceof arguments.callee)) return new arguments.callee(); this.version = '1.2.3' })(); console.log($.version); // '1.2.3'
- furgooswft13 7y agolol. But yes, I do really want to abuse the spec. You could also do this: var $ = (function(){ this.version = '1.2.3'; return this; }).call({}) console.log($.version); //1.2.3 But that's not quite as ugly so I guess I lose some points.