1

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?

James Lemon
  • 428
  • 4
  • 16
  • 1
    `$(run)` is one of syntax used for [document-ready](http://api.jquery.com/ready/) hanlder – Satpal Mar 18 '15 at 07:02
  • 1st and 2nd are IIFE.. second one is a safe guard for code minification.. 3rd one is document ready – Arun P Johny Mar 18 '15 at 07:03
  • So what's the difference between `(function(){` and `+function(){` ? – Mox Shah Mar 18 '15 at 07:04
  • 2
    This [JavaScript plus sign in front of function name](http://stackoverflow.com/questions/13341698/javascript-plus-sign-in-front-of-function-name) might help – Satpal Mar 18 '15 at 07:04

1 Answers1

0

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 );
}
dfsq
  • 182,609
  • 24
  • 222
  • 242