Monday, January 6, 2014

Variable Scoping in Javascript

It is always important to make use of VAR to declare variable identifiers. If you miss doing this , there are two implications.

1. It is then by default act as GLOBAL variable.

2. Chances are these variables will be overwritten everytime developers uses same variable name across the modules. This is worst defect and sometimes difficult to figure it out.

/* Declared globally. */

function FindTruth(id) {


}


// Later in your page, another programmer adds…

var FindTruth= $(‘Overwritten-False-Fact’); // The FindTruth function just got

// overwritten.

Namespacing- Best Practice



/* Using a namespace. */

var MyNamespace = {

FindTruth: function(id) {


},

// Other methods can go here as well.

}

// Later in your page, another programmer adds…
var Findtruth= $(‘Overwritten-False-Fact’);// Nothing was overwritten.

In JavaScript Object Oriented programming this is Singleton pattern.

Now one can access method using MyNamespace.Findtruth(Id);

We can even structure it separately and then later add group of methods to decorate as library.

/* Super namespace. */

var SuperLib = {};

SuperLib.Common = {

// A singleton with common methods used by all objects and modules.

};

SuperLib.DataAccess= {

//Hold and transfer data

};

SuperLib.Helper= {

//Html Helper

};
Post a Comment