Recently I’ve started overhauling all our old javascript libraries to make them more object-based and easier to maintain. As a result, I’ve needed to get familiar with how to create objects and assign properties and methods. This is surprisingly easy in javascript:

Creating an object (Constructor) with properties:

function MyObject(param1, param2)
{
    this.myProperty = param1;
    this.myProperty2 = param2;
}

You can then create an instance of the object like this:

var obj = new MyObject(1, 2);
alert(obj.myProperty);

Creating an object’s methods:

function MyObject(param1, param2)
{
    this.myProperty = param1;
    this.myProperty2 = param2;

    method1 = myFunction;
}

function myFunction()
{
    echo(this.myProperty);
}

You can then call the method for the instance of the object we created above. All methods have access to “this” and can access all member variables:

var obj = new MyObject(1, 2);
obj.myFunction();

Now add as many functions and properties as you need to the object. Its that easy!