If you have attended any of my sessions on beginning Client Side Development you might have heard me talk about ensuring that you do not promote the public namespace. For SharePoint/O365 Developers who are starting to learn client-side the concept of namespaces are common in C#, but not as common in JavaScript. The whole purpose of developing under a namespace is to ensure that your variables do not collide with other variables, resulting in broken functionality, errors, etc.

The approach that I take to address this is by creating a unique object and then working under that object as a pseudo-namespace.

For example:

var jaredApp = jaredApp || {};
jaredApp.GetData = function(){

console.log(“This functionality exists under jaredApp”);

}

You could follow that approach and build out your other functions – and then it is as easy as jaredApp.GetData(); to call the function. The benefit of this is all of your variables fall under jaredApp (or whatever you decide to call it), rather than binding to the window object which is where variables are assigned by default – this is also referred to as the global namespace.

There are a couple of other approaches such as the immediately invoked function execution (IIFE) which looks something like this:

(function(){
console.log(“This functionality exists temporarily within this invoked function”);
})();

The nice things about the IIFE is all variables created within it are scoped within that function therefore they would not be bound to the global namespace, which prevents collisions.

Happy SharePointing & JavaScripting!

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