Object Oriented Programming with JavaScript

JavaScript is a powerful and old language that was not thought to work with objects, though, we can make it a bit object oriented implementing our own objects and classes like this:

Create a class

To make a class we can directly build it a constructor and inside it place all the class properties and methods like this:

function CreateMyObject() {
    //Here all the stuff
}

Adding public and private variables

You can make a public variable using the keyword this.

function CreateMyObject() {
    this.publicVar = 'Im public';
    var privateVar = 'Im private';
}

Adding public and private methods

Following the same as before, but we have to ways of setting the pointer to the method.

function CreateMyObject() {
    this.someMethod = someMethod;
    function someMethod() { 
        alert('Hello Im a method');
    }
    this.someOtherMethod= function () {
        alert('Hello Im another method');
    }

    function privateMethod(){
        alert('Im a private method.');
    }
}

With the first option you could make a list of public methods in the top and then write the methods down, with the second you don’t need to maintain a list.

Putting all of it together

Just to have it as an example:

function CreateMyObject() {
    // Properties
    this.publicVar = 'Im public';
    var privateVar = 'Im private';

    //Methods
    this.someMethod = someMethod;
    function someMethod() { 
        alert('Hello Im a method');
    }
    this.someOtherMethod= function () {
        alert('Hello Im another method');
    }
    function privateMethod(){
        alert('Im a private method.');
    }
}

Using it

var MyObject = new CreateMyObject();
alert(MyObject.publicVar);
alert(MyObject.privateVar); // This will not work. Its private!!
MyObject.someMethod();
MyObject.someOtherMethod();

Thanks to webmonkey, about and codeproject.

Close Bitnami banner
Bitnami