Chaining functions in Javascript

Most of us are aware of the all famous Jquery demo

$("p.neat").addClass("ohmy").show("slow");
which is a gem of an example of chaining functions.

There are many resources out their on which demonstrates various ways of chaining javascript function but, I always like to explore my own ways of doing things, let people call it re-inventing the wheel, but like doing that I like to make my own wheel! [ Enough of Nihilism! ]

Below is a simple code that /me managed to pull, which is closest to the Jquery demo and as always there might be better ways of doing the same, do let me know your way of doing this.

$ = (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 () {
            var displayVal = window.getComputedStyle(self).display;
            if(displayVal === 'none') self.style.display = "inherit";
            return this;
        },
        hide: function () {
            var displayVal = window.getComputedStyle(self).display;
            if(displayVal !== 'none') self.style.display = 'none';
            return this;
        },
        toggle: function () {
            var displayVal = window.getComputedStyle(self).display;
            displayVal !== 'none' ? self.style.display = 'none' :
            self.style.display = "inherit";
            return this;
        }
    };
 
}(document));

P.S : Thanks to ImBcmDth for suggesting, window.getComputedStyle(self).display;

With this one can do something like :  $.get('p.neat').addClass().show()

Share this