View Full Version : Chaining methods

07-10-2006, 02:44 PM
Some javascript libraries like jquery or prototype can chain methods like so


I can't figure out how this is done, does anyone have a simplified example?


07-10-2006, 04:28 PM
That notation isn't chaining of methods.

What is happening there is you have an object being returned by $. That object has a method called html, which is being called. That method returns an object that has the method show, which is being called. Expanded it looks like:

var x = $('element');
var y = x.html('blah');

But because $ returns a pointer, there's no reason to store it in x:

var y = $('element').html('blah');

But the same is true for html, it returns a pointer to an object, why store it?


Hope that clears it up.

07-10-2006, 04:48 PM
Well, you can do :


so the order of the functions doesn't matter. There are also no duplicate functions.

07-10-2006, 04:54 PM
You'll have to look into the library your using, but based on the syntax rules of javascript, the object returned from $ must have both show and html methods for the statements you posted to be true.

I assure you that your library cannot change the rules of the language, this is object notation, and those are methods being called on objects.