-1

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

0

2 Answers 2

2

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".

Sign up to request clarification or add additional context in comments.

7 Comments

I think the main goal with that kind of syntax is to use the $ sign inside..(which he didnt)...no ?
@Royi - You are right, the (function($){})(jQuery); is very common in plugins, but here the code isn't using the $ variable, so it isn't really needed.
@RoyiNamir: That syntax is usually used for two reason; a) to ensure $ points to jQuery, and b) to provide a scope where private variables can be defined. In this situation, as \@Kobi pointed out, the author is using a closure for (b); without defining the closure 1) other 3rd party code could overwrite our declaration of originalAddClassMethod, or we could overwrite theirs.
@Royi - Yes. In JavaScript, you need a function to change the closure - it doesn't make a difference if they are named functions or anonymous.
@RoyiNamir: They're almost the same.. but you leave yourself in a catch-22 situation, as one of the reasons we're using a closure here is to prevent overwriting any global variables. By declaring a function and then executing it, you run the risk of overwriting any variable named Do.
|
2

If you use var outside of a function you still create a global variable (because that's the scope you are in). So you need to wrap all code in a function to get a new scope.

The fact that he did not use the function to ensure $ points to jQuery but used jQuery all the time instead just means that he was somehow masochistic and wanted less-readable code. ;)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.