Object oriented JavaScript

JavaScript was not invented in an Object Oriented way as most programmers know it, that is there is no concept of ‘class’ in JavaScript. Anyway we can use and create objects as a list of key and values in the next way:

{
  field: ‘value’,
  operation: function(){
    //Do something
  }
}

We can go a step beyond simulating the constructors we all know from other languages, the trick is to create functions which make object instances for us. The first thing we have to know is that in JavaScript every function has a context object called this, and the second is that it exists a new operator to create new function instances. Using both concepts we can construct a function which acts as a class. An example is better than a thousand words, I think its enough clear:

var MyClass = function(constructorParam){      

  this.publicField = constructorParam;

  this._privateField = constructorParam; //Note the _ symbol to make it private

  this.publicMethod = function(param1,param2){
    this._privateMethod(param1); //The function can only be called from within object’s functions
    //Do something else..
  }

  this._privateMethod = function(param1){
    //Do something private
  }
}

Once that code is included in your page you can use your fake class to work in JavaScript in a fashionable object oriented way:

var myInstance = new MyClass(’some value’,’some other value’);
var theSomeValueString = myInstance.publicField;
myInstance.publicMethod(theSomeValueString,‘a third value’);

I wish this trick help you to mantain your AJAX code a bit more organized. See you soon!

2 comments so far

  1. clintonskakun on

    JavaScript, as you said, “was not invented in an Object Oriented way as most programmers know it”. It’s a little hard for me to understand at first. There are some pretty cool things you can do with OOP JavaScript.

  2. Javier Toledo on

    The most useful thing i have done with that is to create view objects that generate different parts of the web. In this way you can obtain ultra fast loading nested interfaces while maintaining the code organized. I will post about that in the future :-)


Leave a reply