1

Specifically, how can I write prototypes that allow chaining, such as the following:

$('myDiv').html('Hello World').fadeIn('slow');
asked Aug 8, 2011 at 22:36

4 Answers 4

5

The technique you're describing is called fluent interface, and it involves returning the same kind of object from all chainable functions. That object's prototype contains the function definitions.

The linked article includes example code in various languages, including javascript.

answered Aug 8, 2011 at 22:38
Sign up to request clarification or add additional context in comments.

Comments

1

Just return the appropriate stuff from the functions. The basic rule of thumb is take any method that would normaly return nothing and make it return this instead.

function Constructor(){};
Constructor.prototype = {
 foo: function(){
 console.log('foo');
 return this;
 },
 bar: function(x){
 console.log('bar', x);
 return this;
 }
}
var obj = new Constructor();
obj.foo().bar(17).bar(42).foo();
answered Aug 8, 2011 at 22:40

Comments

1

In that particular situation, each method returns this. So:

// ... this has to be the most impractical class I've ever written, but it is a
// great illustration of the point.
var returner = new function() {
 this.returnThis = function(){
 console.log("returning");
 return this
 }
 }
 var ret2 = returner.returnThis().returnThis().
 returnThis().returnThis() // logs "returning" four times.
 console.log( ret2 == returner ) // true
answered Aug 8, 2011 at 22:41

Comments

1

Chaining example:

var avatar = function() {
 this.turnLeft = function {
 // some logic here
 return this;
 }
 this.turnRight = function {
 // some logic here
 return this;
 }
 this.pickUpItem = function {
 // some logic here
 return this;
 }
};
var frodo = new avatar();
frodo.turnLeft().turnRight().pickUpItem();
answered Aug 8, 2011 at 22:41

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.