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);
Defines the
Libproperty of the Object it’s called on, and is immediately called onthiswhich is typically thewindow. It may instead refer to the Object that owns the method in which it is called.Defines the
Libproperty ofwindowregardless of where it’s called (although it’s also called immediately).Defines the
Libproperty of the object passed to the function. It’s called immediately, but will result in an error unless you’ve defined a value forglobalin the current scope. You might passwindowor 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
Libitself).All of these functions return
undefinedand only the first could be usefully applied as a constructor (with the use ofnew), so it would seem they are nothing more than initializers for the frameworks.