Web development Birmingham

How to write object oriented javascript / jQuery

Javascript basic object / class stucture

Not everybody realises this but you can actually write in an object oriented manor using JavaScript. This works regardless of whether jQuery is in place or not.
An interesting feature of JS is that functions can be variables and these functions can have sub variables and sub functions, and so on. For example:

var parentFunction = function(){

var protectedValue = ‘variable’;

var childFunction = function(){

alert(protectedValue);

}

childFunction();

}
var object = new parentFunction();

The above code would alert ‘variable’ when run. Notice how parentFunction has a childFunction within it and that the childFunction is able to use variables that have been defined in the parent. Nice! It’s worth commenting that if you were to try and access the protectedValue variable outside of the parent Function then this would not be allowed.

Public / private javascript variable and function equivalents

Though the above example works well we are unable to call functions outside of parentFunction that are contained within it (i.e. essentially public function), also as order of execution matters you have to take care to only call functions if they have first been defined above the code you are writing.

So, with this considered here is how we create JavaScript objects to solve some of these problems. Example:

var parentFunction = function(options){

var privateValue = ‘private/protected variable’;
this.publicValue = ‘public variable’;

 

this.construct = function(options){
}

 

this.childFunction = function(){

alert(protectedValue);
alert(this.publicValue);

}

 

this.construct(options);

}
var exampleObject = new parentFunction({ });
exampleObject.childFunction();

Some things to note about the above code:

  • Now think of parentFunction as if it is a class as it will behave in a similar way.
  • You are able to create an object instance of a function e.g.
    var exampleObject = new parentFunction({ });
  • We have mimicked the functionality of having a constructor by having a construct function that is called at the end of the parentFunction. You should now write any initialization functionality within the construct function. This allows functions to exist anywhere within the parentFunction and be called from anywhere regardless of it’s location relative to your function calls.
  • The options parameter can now just contain a JSON array of variables that you load into the variables from with the constructor.
  • We have used this.function and this.variable declarations to associate variables or functions directly to the object that they belong to. This is beneficial as you can now use these externally with the right syntax. So exampleObject.childFunction() calls the childFunction from within the parentFunction.

Encorporating other best practices

Now if you get the above concepts let’s go one step further and demonstrate how we can use jQuery to make loading parameters super simple. I bring this up as it is common practice within jQuery modules. Example:

var parentFunction = function(options){

var vars = {

privateVar: ‘original Value’,
another: ‘test’

}

 

var root = this;

 

this.construct = function(options){

$.extend(vars , options);

}

 

this.childFunction = function(){

alert(vars.privateVar);

}

 

this.construct(options);

}
var exampleObject = new parentFunction({ privateVar : ‘new Value’ });
exampleObject.childFunction();

In short, the above function would alert ‘new Value’. Because we have used JSON to store variables within our class and as a parameter on constructor we can now use the $.extend jQuery function to make short work of loading variables into our object. All $.extend does is take one json array and overwrite / add any values that are within the second json array in it’s parameter (e.g. variables within vars will be added or overridden from what is contained within options).

Now, you may be wondering why we have written var root = this? Well, say you are writing some jQuery that loops through some elements on a page, e.g.

var example = function(){

this.variable = ‘hello’;

 

$(‘div’).each(function(){

alert(this.variable);

});

}

In the above example this.variable is technically undefined at the point it has been run as the .each function within jQuery sets the ‘this’ variable to be an object representation of the div tag that it is currently accessing from the loop.

So this root variable now becomes very handy to allow you to call a parents variables within these sort of loops (it is also useful for the success function on AJAX calls), e.g.

var example = function(){

this.variable = ‘hello’;
var root = this;

 

$(‘div’).each(function(){

alert(root.variable);

});

}

The above code would now successfully echo “hello” if example were to be run.

Did you find this article useful? Sharing is a great way to show support, and ensures that we can continue to create more quality articles:

Get a free quote