Over a million developers have joined DZone.
Platinum Partner

Chaining Functions in JavaScript

· Java Zone

Discover how AppDynamics steps in to upgrade your performance game and prevent your enterprise from these top 10 Java performance problems, brought to you in partnership with AppDynamics.

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

$("p.neat").addClass("ohmy").show("slow");


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) {
            self.classList.add(new_class);
            return this;
        },
        show: function () {
            self.style.display == 'none' ? self.style.display = 'block' : 
            self.style.display;
            return this;
        },
        hide: function () {
            self.style.display !== 'none' ? self.style.display = 'none' : 
            self.style.display;
            return this;
        },
        toggle: function () {
            self.style.display == 'block' ? self.style.display = 'none' : 
            self.style.display = 'block';
            return this;
        }
    };
 
}(document));


With this one can do something like: 

$.get('p.neat').addClass().show()

The Java Zone is brought to you in partnership with AppDynamics. AppDynamics helps you gain the fundamentals behind application performance, and implement best practices so you can proactively analyze and act on performance problems as they arise, and more specifically with your Java applications. Start a Free Trial.

Topics:

Published at DZone with permission of Hemanth HM , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}