For large objects it may be easier to use Ex1 over Ex3 as it needs
less identation (Google has limit for line length in its coding
guideline).
The advantage of using the module pattern is that you can define
"private" variables for your object.
goog = (function(){
var secret = "cannot be accessed directly from outside";
return {
show: function(){
alert(secret);
},
// ...
};
})();
I think Google doesn't use closures for private variables because of
the small performance penality it has (variables are searched up the
scope-chain). As far as I know they're utilizing Closure Compiler's
ability to guard private members (using @private):
/**
* A simple private memeber of goog.
* @private
* @type {String}
*/
goog._secret = "cannot be accessed directly from outside";
You can read more about Google CC OOP features at:
http://calendar.perfplanet.com/2010/coding-better-object-oriented-javascript-with-closure-compiler/
- Balázs
2010/12/16 bawigga <[email protected]>:
> What is the correct nomenclature for the following ways of writing JS. I
> understand how each example works, but I don't know how to put the following
> patterns into words. I also don't know when it's best to use one pattern
> over the other (perhaps just preference)?
> I personally prefer ex 2/3 as I feel as though it keeps my code a lot
> cleaner, and easier to maintain. It would seem ex1 doesn't really help in
> code maintainability as you still have a bunch of seemingly random unrelated
> functions within a single namespace.
> I also found that the google closure lib uses ex 1, and jquery seems to use
> ex 2/3. Why would they choose one over the other?
>
> Google Closure -
> http://code.google.com/p/closure-library/source/browse/trunk/closure/goog/base.js?r=544
> - namespace pattern?
> jQuery - http://code.jquery.com/jquery-1.4.4.js - using object literal?
>
> // ex 1 (namespace pattern?)
> goog.a = function() {
> //do something
> };
> goog.b = function(){
> //do something
> };
> // ex2 (module pattern?)
> goog = (function(){
> return {
> a: function(){
> // do something
> },
> b: function() {
> // do something
> }
> };
> })();
> // ex 3 (literal pattern?)
> goog = {
> a: function(){
> // do something
> },
> b: function() {
> // do something
> }
> }
>
> --
> To view archived discussions from the original JSMentors Mailman list:
> http://www.mail-archive.com/[email protected]/
>
> To search via a non-Google archive, visit here:
> http://www.mail-archive.com/[email protected]/
>
> To unsubscribe from this group, send email to
> [email protected]
>
--
To view archived discussions from the original JSMentors Mailman list:
http://www.mail-archive.com/[email protected]/
To search via a non-Google archive, visit here:
http://www.mail-archive.com/[email protected]/
To unsubscribe from this group, send email to
[email protected]