Possible Duplicate:
how does jquery chaining work?
This is a normal thing you would see in a jQuery code:
$("div.selected").html("Blah.");
So, in the above code, in the function $(), it has a function called html(). And what I don’t understand is, what I normally will do is:
funcA("blah"); //normal function, cool.
funcA.funcB("blah"); //normal function in an object, still cool.
and now this is confusing:
funcA("blah").funcB("blah") //huh??
How can funcB knows the arguments in funcA?
How can jQuery achieve this?
Thanks.
In this one, the
foofunction returns an object containing whatever methods you wish. So when you callfoo, you receive this:elemis present from your call tofoo. If you were to add aconsole.log( elem )at the top ofbar, you’d see that it’s the same thing as what you passed tofoo.This is a little more complex, and actually divided into two.
Who doesn’t love prototypical inheritance mixed with classical inheritance names? Anyway…functions act as both regular functions and as constructors. Meaning, when called with the
newkeyword, two special things happen:thisinside of thefoorefers to a freshly made copy offoo.prototypefoo.prototypeis returned (unlessfooreturns an object)Note that
foo.prototypeisn’t a magic value. It’s just like any other object property.So, inside the
foofunction/constructor, we’re merely settingfoo.prototype.elem, but not directly. Think of it like this (a little inaccurate, but it’ll do):foo.prototypeis the blueprint of a product. Whenever you wish to make more, you use the blueprint – duplicate what’s inside, pass it along. Inside offoo,thisrefers to such a replication of the blueprint.However, by explicitly setting values on
foo.prototype, we’re altering the blueprint itself. Wheneverfoois called, it’ll be called with this altered blueprint.Finally, once
foois finished, the replication (the duplicated blueprint, but afterfoohas done stuff with it) is returned. This replication contains the original blueprint, and everything else we might have added – in this example,elem.We create a nameless function and immediately execute it.
Like all other functions, they can return values. And these values can be captured into variables.
So:
Returns a function which receives an argument, and that function is now assigned to
foo.The insides of the function:
Is to ensure the special conditions I’ve spoken about above – it ensures that a new copy of the blueprint is manufactured, by explicitly doing the
newoperation. This can actually be replicated like this:As long as you always call
foowith thenewkeyword.