Making chainable methods for your js Objects

Making your own chainable methods in javascript is pretty straight forward, since all you have to do is to return the ‘this’ object in the constructor function and methods you create for your object. Let’s create for example a Car constructor function, so we can create car objects and add some chainable methods to it.


function Car(){return this;}
Car.prototype.wheels = 4;
Car.prototype.startEngine = function(){ console.log('starting engine....'); return this;};
Car.prototype.speedUp = function(){ console.log('speeding up...'); return this;};

Notice that the constructor function and the startEngine and speeeUp methods return ‘this object’, which refered to the objects that we’ll create;
Now, that we’ve created our car constructor function, with wheels property and startEngine and speedUp methods, lets create a new car and invoke their methods in a chainable jquery like fashion:


car1 = new Car;

car1.startEngine().speedUp()
starting engine....
speeding up...

We can add more methods to our car object and they will be chainable too..

Car.prototype.brake = function(){console.log('car is braking...')};

car1.startEngine().speedUp().brake()
starting engine....
speeding up...
car is braking.

Thalt’s all folks, make your methods return the ‘this’ object and save some key strokes is your scripts…



Cross-platform mobile apps development with javascript

This post present various cross-platform application frameworks for developing mobile applications using html, css and javascript.

Good Javascript Resources

This post presents some of the best Javascript resources available on the web.

Why Javascript?

This post explains why javascript is the main topic of this blog.