Tuesday, 27 January 2015

Objective thinking in JavaScript

It seems all too common that small projects grow to become big projects and then problems happen. Something that is very frustrating is when your JavaScript code starts to act goofy and you cannot figure out why. A lot of times it is because you are over lapping the name space and a value is getting altered in some other section of code that you did not expect. This can kill a project, it can become so hard to debug that you eventually scrap the code and move on.

Before you write a single line of JavaScript, think about how you can objectify it. In JavaScript you can wrap your code in object like statements so that name space does not get clobbered by other code.

Notice how the functions are set as variables and calls to them are invoked as if it was a real object language.



function myobject() {
   var MyVar = 0;

   this.PageSetup = function() {
      var _this = this;
   }

   this.SendCommand = function(Url) {
      var GetHttp = new XMLHttpRequest();
      GetHttp.open("GET", Url, true);
      GetHttp.send(null);
   }
}; // end of object

var myobject1 = new myobject();

myobject1.SendCommand("mydomain.url/doStuff");

No comments:

Post a Comment