Code Dissection (or the Frog’s Revenge)

Here’s a piece of code that I have came across and pasting here in order to figure it out:

That’s right. This snippet is taken from the earlier discussed Lavalamp menu. But now we are going to dissect it.

So first step – the anonymous function that wraps the whole deal and gets an argument $. This is a general recommendation when designing a plugin – we pass the jQuery reference for $ as an argument of an anonymous function, to set up a closure and thus avoid collision with other scripts in the page, that may also use the $ sign.

Everything that we need for the plugin is inside this anonympus function.

Next, within this closure, we add a new function property to jquery’s fn object. This function’s name is the actual plugin’s name.

Most important to remember at this stage is that ‘this’ actually refer to the object we have just created – i/e/ the plugin itself, and not to the element it is applied on.

Next we deal with our constructor’s parameters: o. Basically o is an object that contains the properties speed, type of effect an a callback function. o is also extended by any argument passed through. If no argument is passed through – then o is extended by an empty object.

Next we iterate through all elements in the documents that are asigned by this onbjects – for example – all elements that has the class name ‘lavaLamp’, and for each we apply all the object’s properties and methods. We always define the properties first, separated by commas.