I am a bit new to reusable plugins for jquery. I have ran across this code several times and can't figure out exactly what is going on.
(function( $ ){
...
})( jQuery );
Can any one enlight开发者_Python百科en me?
It allows the author to use the $ function within the plugin without exposing it to the global scope - just keeps things a bit cleaner outside of the plugin itself.
I believe this is best practice for developing jQuery plugins - sure I saw it mentioned in the docs somewhere!
It creates an anonymous function and executes it immediately, passing it jQuery
as a parameter. Since the anonymous function accepts a parameter $
, within the function $
is the jQuery
object, allowing you to use $
for jQuery objects as you're used to even if $
is being used by something else (such as another library) outside the function. Wrapping code in an anonymous function like this protects against variable naming collisions, because any variable defined inside the function is limited to that function's scope.
function( $ ){ /* … */ }
is an anonymous function that is directly called with jQuery
as parameter. So $
inside the anonymous function is the same as jQuery
.
精彩评论