3 Quick JavaScript Tips for .NET Developers
posted by John with 17 comments
Yesterday at the DevConnections event I had to make an emergency speaking appearance for a speaker who became suddenly ill. Luckily that talk was a topic I know well (JavaScript intro for .NET developers), I was available, and I didn’t freak out
I grabbed the speaker’s deck and used it as a guideline, but I spent the majority of the time in jsfiddle.net writing examples. The audience was really interactive and grasped the basics pretty quickly. The topics that we spent the most amount of time discussing as a group where regarding namespaces, functions and objects. So I thought I might include 3 of the examples here on my blog.
Namespacing
Namespacing is an important (and easy) way to make sure your objects do not collide with other javascript libraries. There are many ways to handle namespacing, but the way I like to start with is dead simple. This example shows that all variables hang off the ‘my’ namespace. I like using ‘my’ because its short and sweet.
Creating an Object Literal
Objects can be created in a variety of ways. But the most common you will see in demos is the object literal. The reason? Its short and sweet. Objects can be created simply by setting a variable equal to an open and close curly brace pair, as shown below. Then add properties as needed. I often use this syntax for simple objects (not a lot of logic, mostly properties and a few methods).
The ‘this’ keyword does work with the object literal, though once you get into nesting functions it can get unwieldy unless you manage ‘this’. That’s often when I use one of a few techniques such as setting ‘this’ (at a place where you know what ‘this’ represents for certain) to a variable called self. But I’ll hit that topic in a later post.
I most often use object literals for passing arguments to functions
Creating an Object from a Function
You can also create objects through functions. While I prefer using a pattern such as the Revealing Module pattern for this, the simplest way to create an object from a function is shown below. Note that use of ‘self’ in here to represent ‘this’. It may not be needed in all cases but it’s a good habit to get into that has saved me many times. A friend of mine actually uses the word ’me’ instead of self … says its twice as fast ![]()
Rick Arthur on said:
Not only did you not ‘freak out’, you did a great job with the presentation yesterday! Thanks for filling in.
Antonio Castro Jr on said:
Nice post John.
Is there a way of having namespaces like:
companyName.System
I tried out but it failed.
john on said:
Antonio – quickest, simplest way is to do something like this:
var companyName = companyName || {};
companyName.system = {};
Rajasekharan Vengalil on said:
Or if you’d like something a bit more generic for defining namespaces then you might find the following useful:
http://jsfiddle.net/avranju/x7HDF/
j5c on said:
The idea above has a slight problem: If companyName.system already exists and has values in it, the values will be obliterated.
You could do:
var companyName = companyName || { };
companyName.system = companyName.system || { };
but that require setting an object to itself which may (depending on the engine) need a lot of linking / unlinking. So. I’d prefer the less compact, but less invasive:
if (companyName)
{
if (! companyName.system)
companyName.system = { };
} // if
else
var companyName = { system: { } };
However, if you really do want to do fancy single line short circuiting:
var companyName =
( companyName // See if companyName already exists
&& (companyName.system || (companyName.system = { })) // companyName exists. Check / create system
&& companyName // Return companyName with new / old system
)
|| { system: { } }; // companyName was not found. Create it with system inside
but jsLint would object to the ‘=’ in the expression.
Personally, I’d add to any of the above:
var system = system || companyName.system;
so that if yours is the only namespace with a sub-namespace of ‘system’, you can save having to add companyName as a prefix; but if another ‘system’ is already defined you do not replace it.
john on said:
Yep, there are much more elegant ways to do this … I was just doing the quick and dirty technique. I have an article coming out in one of my columns that explains more about namespaces, like what you mention as its an important topic.
Elaine on said:
I agree with Rick. You did a great job! Glad we were able to have this session and it wasn’t cancelled.
john on said:
Rick/Elaine … thanks so much. I had a great time and it convinced me to create a JavaScript for .NET developers class. I think it could be quite helpful.
All of you had some awesome questions. I loved the interaction.
Rahul Sarkar on said:
Loved it. Thanks. The project I am working on , uses loads of javascript and it is moving towards becoming almost unmanageable. I think this use of namespace is a neat way of organizing the clutter! I will get my team to adopt this rightaway!!!
Rob on said:
I normally define a “namespaces” in this manner:
var companyName = {
system: {},
otherThing: {}
};
I then make sure that this is the first thing to load before invoking any calls/references to the namespaces.
john on said:
Rob – that works too. Though you have to make sure its first, as you said. Otherwise you have issues.
The best solutions are to create a namespace function that generates the namespace for you if it doesn’t already exist. Crockford has a few examples he posts on how to do this, but frankly there are lots of ways to do it. So just choose your own.
john on said:
Rahul – Glad you liked the session. Thanks. JavaScript is pretty cool once you learn how to manage it.
Anonymous on said:
Hi. Nice Post.
I am new to coding. I want to learn Javascript. Can u guide me where to begin from ? I mean which books or web-tutorials would you recommend?
Vitor Canova on said:
Very interesting. Instead of “self” and “me” I use “that”.
Moana Peck on said:
The best solutions are to create a namespace function that generates the namespace for you if it doesn’t already exist..
Ishmael Vaughan on said:
I think it could be quite helpful.All of you had some awesome questions. I loved the interaction.
Jasper Manning on said:
The namespace of the method taught in this blog is very useful for me.JavaScript is pretty cool once you learn how to manage it.