javascriptjqueryjquery-pluginsiife

Jquery plugin syntax explained?


Ive seen some plugin code in jQuery

one of them is to overload the addClass method in jQuery (example : when you addClass - call myfunction ()).

(function(){

    var originalAddClassMethod = jQuery.fn.addClass;

    jQuery.fn.addClass = function(){
        // Execute the original method.
        originalAddClassMethod.apply( this, arguments );

        // call your function
        // this gets called everytime you use the addClass method
        myfunction();

    }
})();

the thing which i dont understand :

Why did he create a closure ?

I could use a private members inside a normal func with the var and it still be visible to the local scope only.....so ?

can you explain that to me ?

what does he earn from that closure ?

I would have understand that if he sent the $ sign to the function ...but he didnt


Solution

  • I think the closure was added so that the variable originalAddClassMethod isn't defined in the global scope (or parent scope), and is private to the plugin.

    You said:

    I could use a private members inside a normal func with the var and it still be visible to the local scope only.

    This is exactly what was done here: The function is anonymous, but still "normal".