Some clarity for beginner Javascript developers. Because someone is always a beginner, unless the language is dead.

What does this mean?

var MyObject = MyObject || {};

If you have your JavaScript built into several files, then this is stating that use that instance, and if none exist, then create a new instance. Think of it as a means to create a namespace for your code. Personally, I think of it more as creating a static state-full class, that has a life span of one page load.

MyObject = {
          SomeVar : {},
          SomeFunction : function (value) {},

Your object, that was created above now have some public interfaces. Note, when you create a class this way, all of your interfaces are public. Think of it like a JavaScript variable. Look at this:
var X = {x:1,y:2,z:[1,2,3]}; So X[x] == 1, where as X[z] is an array. So X is a complex variable. This means that a var can be a whole lot more than just a primitive value.

With that in mind, MyObject has a variable called SomeVar, and a function called SomeFuntion.

If you really want to trip on this, you can treat SomeFunction as an instance of an anonymous delegate, and overwrite it later like this MyObject.SomeFuntion = function(valA, valB){}; Though, I don’t recommend changing the parameter count when you do overwrite a function.

Also, when you call the function, always use the parentheses, otherwise you aren’t executing the function, you are getting an instance of the function. With that in mind, you can have overloads of functions too.

MyFunction : function(){},
MyFunction : function(var1){},
MyFunction : function(var1,var2){},

Note that overloading only works with parameter count, since there are no distinction of parameter types.

Also note, that you can use addMethod, or call the objects prototype, and modify it. Regardless, you can do some really nifty stuff.

Some follow up material, and links to some solid libraries:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.