Writing unobtrusive JavaScript

Namespaces

Important principle – since all JavaScript referenced by a page is essentially grouped as one giant JavaScript file, we need to be careful with not using the global namespace (to avoid conflicts).

So pick a namespace for your JavaScript code and keep using that.

E.g. instead of doing

var planet = { // went to global namespace
   name: "Earth",
   sequence: 3
}

Keep planet in a particular namespace (say “MYNAMESPACE”) as below. But first we need to create the namespace first – well a var that we will treat as a namespace. Another example where JavaScript’s malleability allows it to take on features not exactly inherent to it.

var MYNAMESPACE = {}; 

MYNAMESPACE.planet = {
   name: "Earth",
   sequence: 3
}

However, if you’re declaring variables inside the jQuery ready() function then those vars are going under the jQuery namespace. To illustrate, the following example would print out “undefined” to the console.

$(function() {
   var someString = "I belong in the jQuery namespace";
   console.log(window.someString); // 'undefined'
});

Code snippets based on the Microsoft Virtual Academy’s great introductory series on JavaScript.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s