JavaScript Anonymous Constructor Function: !function(){}();

constructor, function, javascript

Solution

The first line is to ensure that `Application` always exists, and is generally used in cases where it's expected that `Application` already should exist, and the function just augments the existing object. If it doesn't exist, this makes sure that we don't get an error for accessing properties of undefined. Your examples are only equivalent in the case where `Application` does not yet exist. In all other cases, your code will obliterate the existing `Application`, which is almost certainly not the intent.

The comment from Vatev explains what the `!` does. It's another syntax for making the function in question become a self executing anonymous function. (Incidentally, it also takes the return value of the function - which is currently `undefined`, and flips its truthyness, so it evaluates as true. Since the result isn't stored in any variable, though, that's clearly not the purpose.)

Finally, why pass `window` and `Application` into the function and use it there? This is a safety feature, in case other code changes `window` or `Application` later on. It guarantees that within the anonymous function, `window` and `Application` are exactly what you expect it to be. In the shorthand example you gave, this may appear to not matter - after all, why protect these variables if you're using them immediately and not storing them? In many cases, you return something from this function, and then `window` and `Application` would be stored in the closure, so you'd retain the variables. It makes it safe from people who later on decide to say `Application = {...}`.

Problem

I've seen this syntax for creating an anonymous constructor function in JavaScript: ``` var Application = Application || {}; !function(window, Application) { Application.property = {/*...*/} Application.method = function(){/*...*/} }(window, Application); ``` I want to understand what the following parts here: - What is the advantage of using first line (i.e. `var o = o || {};`) vs just stating `var o = (function(){})();`? - Why `!` is used in front of function? - Why would I pass `window` or `Application` as parameters when they are global object? - Is this the most convenient way for anonymous constructor function and how is this better than: 4a) ``` var Application = { property: {}, method: function(){} } ``` or 4b) ``` var Application = (function() { var method = function(){/*...*/} return {method:method}; }()); ```

Original source

Related problems