Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help understanding Twitter bootstraps plugins (jQuery)

I get all of the plugins code except for one line, and due to the way search engines work I cant actually search for my question.

The question is what in the hell is this:

(!function($) {/*....*/})(jQuery);

Why does it say !functions($)?? I'm guessing for the same effect of the $.noConflict() but isn't that why we just use (function($) {/*...*/})(jQuery); it just wraps the dollar sign to our function block. I am completely aware that I could be way off base here, I'm still intermediate in jQuery/js.

If someone could please enlighten me on the effect of the NOT operator before the function statement, i would greatly appreciate it.

Edit: It would appear that i overlooked bootstrap not having (!function($) ... ) but just being !function($)... but you guys helped me in realizing it is just an alternative to ()

like image 660
dhazelett Avatar asked Feb 06 '12 09:02

dhazelett


1 Answers

So there a couple things going on here. Everything is being wrapped in an anonymous function that is executed right away. This is to create a scope for the library so that when the author declares functions and variables they are are not global by default.

With me so far. Ok next thing is the whole ($){...}(jQuery) thing. What is going on here is the author is passing the jQuery library into the anonymous wrapper function as a parameter called $. So in the scope of the anonymous function he can use $ to reference jQuery as you would expect. This is more of a best practices thing because 99% of the time jQuery is already defined as $ in the global scope, but its considered bad form to refer to global variables within a functions scope, and thus he / she passes it in as a parameter.

Still there? The exclamation mark: there is a rule in Javascript that states the first line of a program MUST be an expression (ie not a function declaration aka statement). By prepending the ! the author is turning the declaration into an expression (that returns false). In this case however I don't think the ! is actually required because the declaration is wrapped in () and executed right away. (A function call is an expression)

like image 170
Matthew Avatar answered Oct 01 '22 20:10

Matthew