Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable chainability in a Javascript object like jQuery

Tags:

javascript

I've a question about chainability, look at this code:

document.getElementById('menu').fadeIn(200, function(){ //callback });

How can i make this without jQuery?

Note: the name fadeIn() and fadeOut() are for example, there are not the jQuery functions.

like image 337
Alessandro Cerutti Avatar asked May 17 '26 15:05

Alessandro Cerutti


1 Answers

"Method chaining is a common technique for invoking multiple method calls in object-oriented programming languages. Each method returns an object (possibly the current object itself), allowing the calls to be chained together in a single statement.A method chain is also known as a train wreck due to an increasing amount of methods stacked after another in one line."

//Create an object which contains functions
var obj={
        alert : function(txt){
                alert(txt);
                return this   //return itself
        },
        confirm :function(txt){
                confirm(txt);
                return this   //return itself
        }
}

//Now you can chain as much as you want
obj.alert("This").alert("is").confirm("called").alert("chaining.");

Source:

  • http://en.wikipedia.org/wiki/Method_chaining#JavaScript
like image 62
karim79 Avatar answered May 20 '26 04:05

karim79