Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between anonymous functions

I'm reading more open source javascript frameworks and found more ways of how to create anonymous functions, but whats is different and best way?

(function() {
    this.Lib = {};
}).call(this);

(function() {
    var Lib = {}; window.Lib = Lib;
})();

(function(global) {
    var Lib = {}; global.Lib = Lib;
})(global);
like image 277
kichu Avatar asked Jul 26 '26 12:07

kichu


2 Answers

(function() {
    this.Lib = {};
}).call(this);

Defines the Lib property of the Object it's called on, and is immediately called on this which is typically the window. It may instead refer to the Object that owns the method in which it is called.

(function() {
    var Lib = {}; window.Lib = Lib;
})();

Defines the Lib property of window regardless of where it's called (although it's also called immediately).

(function(global) {
    var Lib = {}; global.Lib = Lib;
})(global);

Defines the Lib property of the object passed to the function. It's called immediately, but will result in an error unless you've defined a value for global in the current scope. You might pass window or some namespacing Object to it.


These aren't actually different ways of defining "anonymous functions", they all use the standard way of doing this. These are different methods of assigning values to global (or effectively global) properties. In this sense, they are basically equivalent.

Of more significance would be, for instance, how they define methods and properties of the objects they return/construct/expose (that is, how they build Lib itself).

All of these functions return undefined and only the first could be usefully applied as a constructor (with the use of new), so it would seem they are nothing more than initializers for the frameworks.

like image 77
bkconrad Avatar answered Jul 28 '26 01:07

bkconrad


All of them are effectively equivalent (but less efficient and more obfuscated) to:

var Lib = {};

Immediately invoked function expressions (IIFEs) are handy for contianing the scope of variables that don't need to be available more widely and conditionally creating objecs and methods, but they can be over used.

Note that in the last example, I think you mean:

(function(global) {
  ...
})(this);
like image 26
RobG Avatar answered Jul 28 '26 00:07

RobG