Answer Embedded Below in UPDATE 2/ANSWER
Thanks to Joseph for helping me find the answer (even though I don't like it =).
ORIGINAL QUESTION
While doing some research on best practices when using Namepsaces in JavaScript, I came across this definition of the "Model Pattern": http://yuiblog.com/blog/2007/06/12/module-pattern/ .
I've been generally using this pattern since I saw it in YUI2 years ago, and this article gives a nice overview of the concept. But what it does not touch on is why "Self Executing Anonymous Functions" are used in place of "new function". This was asked in the comments, but was not well described by the author. As this article is 4+ years old (and I've not found the answer elsewhere online) I thought I'd bring it here.
It's already within a closure, so? (see: Why is this function wrapped in parentheses, followed by parentheses? which also doesn't answer my question =).
Assuming the following setup code..
var MyNamespace = window.MyNamespace || {};
Which of these is preferred and why?
MyNamespace.UsingNew = new function() {
var fnPrivate = function() {
return "secrets1";
};
this.property = "value1";
this.method = function() {
return "property = " + this.property + ' ' + fnPrivate();
}
};
MyNamespace.UsingSelfEx = (function() { //# <- Added "pre-parens" suggested by chuckj
var fnPrivate = function() {
return "secrets2";
};
var fnReturn = {};
fnReturn.property = "value2";
fnReturn.method = function() {
return "property = " + this.property + ' ' + fnPrivate();
}
return fnReturn;
})();
UPDATE:
It seems that like jQuery, all the cool kids are using "Self Executing Anonymous Functions" (SEAF)! But I just don't get this, as I find it much cleaner to use the .UsingNew approach as you expose the public functions at definition (rather than below in a return that needs to be maintained separately or being forced to use the inline object notation).
The argument for not needing "that = this" doesn't hold water for me for a number of reasons:
- In order to avoid "var that = this" you end up either making a "var obj" plus a return statement (having to maint. a separate definition of what is public) or being forced to use the inline object notation (return {1,2,3}) for your public properties/methods.
- You could always make a private variable of "var that = this" at the top of the class/namespace and use "that" throughout.
Now... I suppose my development style may well make the .UsingNew pattern much easier to manage. My "private" functions are almost always "static" in nature, so I need to pass in the context anyway (supplanting the need for "this"). I have also taken up the habit of using an "abbreviation" namespace, so when I do need access to "this" I simply refer to the full object via the "abbreviation" namespace rather than via it's full path. E.G.:
var PrivateFunct = function() {
var rThis = Cn._.val; //# The abbreviated form of Cn.Renderer.Form.Validation
//...
};
or if it's a Private Static Function...
var PrivateStaticFunct = function(oContext) {
//...
};
Other then the reasons given above, I personally find the .UsingNew approach much more readable in the source. I've got a pretty extensive codebase that uses the .UsingNew pattern here: http://code.google.com/p/cn-namespace/source/browse/Cn.Web/js/Cn/ with the Validation functionality probably the easiest to get your head around in 1 quick read thru. I also use some SEAF functions (see ErrorMessages.js.aspx) but only when they make sense.
I could not imagine having to maintain separate returns to expose the public interfaces at the bottom! Yuck!
Now, don't get me wrong, there are a number of places where a SEAF is very useful in order to enforce the closure, but I personally think it's overused within objects.
UPDATE 2:
Upon further reflection (and thanks to an extended discussion with Joseph under his answer) there seems to be some rules that can be applied to this DEATHMATCH:
Per Douglas Crockford (see: JS we hardly new Ya) Anonymous functions should never use the "new" keyword because:
- It is faster to use an object literal.
- By using new to invoke the function, the object holds onto a worthless prototype object. That wastes memory with no offsetting advantage. If we do not use the new, we don’t keep the wasted prototype object in the chain. (NOTE: prototype calls come after the constructor definition, and as SEAF or "new" anonymous functions are fired imminently one cannot use prototype with them)
- It requires less code to use an object literal. (while true, I have to disagree as I hate the object literal notation, I'd much prefer to use ;'s rather then ,'s as it's more readable).
- It is never a good idea to put new directly in front of function. For example, new function provides no advantage in constructing new objects.
So it seems the meat and potatoes of the matter is this: SEAF's are preferable to var obj = new function() {...};
due to speed and less overhead (no unneeded prototype object). What you have to suffer through is the fact that you are forced to use object literal notation (so ,'s rather than ;'s between your public members) or to maintain a separate list of public objects in a return object.
SEAF's are not advisable when you are intending the function to work as an object constructor as instanceof
will not work as expected (see: creating objects from JS closure: should i use the “new” keyword?).
ANSWER:
- If it's an anonymous function intended to function as a Singleton/Global Static Instance, use SEAF.
If you are intending it to function as a Constructor
(to potentially represent multiple objects) or you are using .prototype, use a "standard" function definition and invoke with "new", e.g.:
function PseudoClass1() {}
var PseudoClass2 = function() {};
var myClass1 = new PseudoClass1();
var myClass2 = new PseudoClass2();
I have to say, I am not happy with this answer ;) I find the .UsingNew pattern MUCH more readable in the codebase, but it is slower and uses more memory then SEAF due to the fact that the unused prototype reference is instantiated and left in the object chain.
See Question&Answers more detail:
os