...

View Full Version : Chaining methods



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

$('element').html('bla').show('fast');

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

Thanks

Beagle
07-10-2006, 03: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');
y.show('fast');

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

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

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

$('element').html('blah').show('fast');

Hope that clears it up.

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

$('element').html('bla').show('fast');
$('element').show('fast').html('bla');

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

Beagle
07-10-2006, 03: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.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum