Last Updated: February 25, 2016
·
1.919K
· javier_toledo

Object-oriented JavaScript, the easy way

This is a very basic technique that helps to maintain your JavaScript code a bit more organized and easy to change. JavaScript is not an Object Oriented language, that is there is no concept of 'class'. Anyway we can use and create objects as a list of key and values as follows:

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

Then we can simulate classes and instances by creating constructor functions: In JavaScript every function has a context object called 'this', and also exist a 'new' operator to create new function instances. Combining both concepts we can write a function which acts as a class:

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); //_privateMethod can only be called from within object's functions
        //Do something else..
    }
    this._privateMethod = function(param1){
        //Do something private
    }
}

Once this constructor is defined it will behave like a class constructor and objects created with it as instances of the class:

var myInstance = new MyClass('some value');
var theSomeValueString = myInstance.publicField;
myInstance.publicMethod(theSomeValueString,'a second value');

There are other ways to declare JavaScript constructors, but this one is for me the easiest to remember and use.

Nowadays most of JavaScript libraries or frameworks come packed with tools to easily manage classes and constructors, and CoffeeScript language even natively support Object-Oriented development.

Any way you do: Happy OO coding!

1 Response
Add your response

the params can be named like intage or strname, i think its helps to make the source code more clear, i dont like to find a function with a param "a", wtf is that?

over 1 year ago ·