Halhelms
SIGN UP FOR MY NEWSLETTER

www.savorgold.com is top on wow gold and runescape gold and World of Warcraft gold provider list for trusted services. Their reputation seems to growing by the minute, which isn't surprising because they are one of the safest sellers of Gold. Delivery speed and customer service are very good. They aslo are giving some bonus items depending on the amount of gold you purchase.

 
 
Halhelms

Recent Comments

Recent Entries

RSS

Mail Call : JavaScript Skeleton

A developer wrote me recently with this plaint: "I'm doing more and more JavaScript, but I don't think I really understand it well enough. There are self executing functions, anonymous functions, anonymous self-executing functions. Then we need to namespace and keep some things private. I've got enough theory. I need some practical help. I'm hoping you can give me some."

I responded:

There is a lot of confusion about JavaScript. I'll try not to add any more to it. One of the reasons for confusion is the looseness of the language. There are many ways to do things. Things look like classes, but they're really functions. One piece of code can be a function declaration or a function expression, depending on its context.

But you asked for practical help. So here's what I do: I start with a JavaScript skeleton that looks like this:

var skeleton = function(){
   // private variables *******
   var x;
	
   // private functions

// initialization ******* ( function init () { // only call private functions or variables! } ) ();

// public API ******* return { methodName : function () {

},

methodName : function () {

} } } ();

At this point, you may be more confused, but let's take it step by step.

First, notice the comments. This skeleton is composed of four sections within an overall self-executing function. (I'll get to that shortly.)

The four sections are:

1. private variables : these are variables that can't be accessed outside of the main function (that main function is called "skeleton").

2. private functions : these are functions that, too, can't be accessed outside of the "skeleton" function.

3. initialization : this is a function used to initialize private variables and/or call private methods.

4. public API : this is what is available to users of "skeleton".

Those four sections are wrapped in a main self-executing function (called "skeleton"). That's another way of saying that we're going to (a) declare a function and (b) run that function at the same time.

Why would we want to do that? It provides name-spacing and private variables and methods. For now, just take that as a given. You can recognize self-executing functions by the () at the end of a function.

Regular Function var funky = function(){};

Self-Executing Function var funkadelic = function(){}();

And, yes, they are somewhat funkadelic at first. But before long, you'll get completely comfortable with them.

OK, so on to the code. You can see that the initialization section is, itself, a self-executing function. I happened to give it a name, but none is really necessary. (Had I left off the name, it would be an anonymous, self-executing function.)

So, let's see the skeleton transformed into a bit of quasi-real code:

var Composers = function(){
   // private variables *******
   var eras = {  
      classical : [ "Bach", "Mozart", "Haydn" ], 
      romantic : [ "Beethoven", "Chopin", "Wagner" ], 
      modern : [ "Bloch", "Gorecki", "Nielsen", "Britten" ] 
   };

// private functions var randomForEra = function( era ) { var arraySize = eras [ era ].length; return Math.floor( Math.random() * ( arraySize ) ); }; // initialization ******* ( function init () { // only call private functions or variables! eras.classical.sort(); eras.romantic.sort(); eras.modern.sort(); } ) ();

// public API ******* return { representative : function (era) { return eras[ era ][ randomForEra( era ) ]; } } } ();

console.log( Composers.representative( 'modern' ) );

The private variables has a hash/map/structure (all words for the same basic idea -- a set of named values).

The private functions section has a single function: randomForEra. It takes the name of an era (such as "romantic"). The variable "eras['romantic']" may have a different number of composers than, say, "eras['modern']", so we want to be sure we provide a number that doesn't walk us off the end of the array (by being too large). That's what randomForEra does.

The initialization section makes sure the composers within each era are sorted alphabetically. Frankly, this makes no sense: I just needed some initialization code and chose this not-very-good example.

Finally, the Public API section has a single function: representative, which takes the name of an era and returns a random representative of that era.

If you study the code a bit, I think you'll get the hang of it. It's definitely not the only way to write JavaScript. It's the way that works best for me. Since you're confused about all the ways to do things in JavaScript, my advice is to start here. Get comfortable with it. Then you can expand your knowledge into other ways of working with JavaScript.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
Tony Nelson's Gravatar Great post. Reminds me of a post from Yahoo (http://www.yuiblog.com/blog/2007/06/12/module-patt...), but your example seems a lot cleaner and more straight-forward.
# Posted By Tony Nelson | 10/13/10 12:37 PM
andy matthews's Gravatar Love it Hal. Well written, and very informative. Helps clear up some confusion for me too.
# Posted By andy matthews | 10/13/10 12:47 PM
Raymond Camden's Gravatar Just wanted to say thank you - this is a great example.
# Posted By Raymond Camden | 10/13/10 12:58 PM
Hal Helms's Gravatar Thanks much, guys. Glad it helped.
# Posted By Hal Helms | 10/13/10 1:17 PM
Aaron Longnion's Gravatar Thanks Hal! (bookmarked.)
# Posted By Aaron Longnion | 10/13/10 2:21 PM
Drew's Gravatar I like that initialization bit, it does have the shortcoming of not being really an class anymore so much as a little application all in its own.

I may be stuck always thinking in Singletons or module pattern as Tony posted, so I think that's the easiest way of understanding JavaScript.

When people ask me about JavaScript, I usually point them to jQuery since it allows them do to what they want easier. I'll include this post too as part of my getting up to speed with JS.

Thanks for the example.
# Posted By Drew | 10/13/10 10:23 PM
Hal Helms's Gravatar @Drew - actually JS doesn't have classes at all -- just objects. I know -- it's confusing, what with them responding to the "new" keyword. But if you want to think about it as a class, you can think of the initialization as a sort of constructor. But I would recommend not bringing the classical OO metaphor to JS. You'll get further faster.
# Posted By Hal Helms | 10/14/10 12:24 AM
Stefan's Gravatar Thank you for this post. It has extended my understanding for Javascript.
# Posted By Stefan | 10/14/10 6:57 AM
 
   
Clicky Web Analytics