HTML5 Zone is brought to you in partnership with:

A GNU/Linux g33k CLI+Web loving computer polyglot. Hemanth is a DZone MVB and is not an employee of DZone and has posted 17 posts at DZone. You can read more from them at their website. View Full User Profile

Chaining Functions in JavaScript

  • submit to reddit

Most of us are aware of the all-famous Jquery dem:


It is a gem of an example of chaining functions.

There are many resources out there that demonstrate various ways of chaining javascript functions, but, I always like to explore my own ways of doing things. Let people call it re-inventing the wheel, but I'd like to make my own wheel! [ Enough of Nehilisim!]

Below is a simple code that I managed to pull, which is closest to the Jquery demo and, as always, might be done in better ways. (You are welcome to let me know of any better way in the comments section or via e-mail.)

$ = (function (document) {
    var self = '';
    return {
        get: function (selector) {
            self = document.querySelector(selector);
            return this;
        addClass: function (new_class) {
            return this;
        show: function () {
   == 'none' ? = 'block' : 
            return this;
        hide: function () {
   !== 'none' ? = 'none' : 
            return this;
        toggle: function () {
   == 'block' ? = 'none' : 
   = 'block';
            return this;

With this one can do something like: 

Published at DZone with permission of Hemanth Madhavarao, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)


First Last replied on Tue, 2012/09/04 - 9:40am

So what's the point here? Returning "this" to achieve chaining?

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.