Normally we'll do some of these :
first type
(function(){
}());
type 2
+function(){
}();
But today I saw this
$(run);
function run(){
//..
}
what is the different of that versus the earlier two?
Normally we'll do some of these :
first type
(function(){
}());
type 2
+function(){
}();
But today I saw this
$(run);
function run(){
//..
}
what is the different of that versus the earlier two?
The third version is technically not the same as first two. The two first constructions are simply a way to write an expression which can be executed, since function declaration (statement starting with function
keyword) cannot be invoked immediately.
The third is different. It is one of the jQuery document ready syntax. If the function is passed into $
function it is either appended to a stack of callbacks to be called on DOMContentLoaded event if it hasn't occurred yet, or - it is called immediately.
Check the jQuery's source code to see how it handles functions in this case. Abstract:
// ...
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready !== undefined ?
rootjQuery.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}