Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
500 views
in Technique[技术] by (71.8m points)

self executing function jquery vs javascript difference

What are the difference among -

First :-

(function () {

    var Book = 'hello';

}());

Second:-

(function () {

    var Book = 'hello';

})();

First and second are similar some how in work..

Third :-

(function ($) {

    var Book = 'hello';

})(jQuery);

What pattern I need to use and where in my coding.. Third module pattern I have seen while I was reading a article related to backboneJS.

What I understood from Third one "self executing function with the argument “jQuery”" ....

Can any please give me some idea about Immediately Invoked Function Expressions (IIFE).

Thanks !!

question from:https://stackoverflow.com/questions/19491650/self-executing-function-jquery-vs-javascript-difference

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In all cases you are doing an anonymous function. I think 1 is the same as 2. In the third case you are passing jQuery as an argument. This is done when you want to encapsulate jQuery within your function's scope.

For instance, in your application, jQuery var could be jQuery. But within your anonymous function you may want to use it as $.

(function ($) {
    //Here jQuery is $
    var Book = $(document.body).text();    

})(jQuery);

//Out of your function, you user jQuery as jQuery (in this example)
var Book = jQuery(document.body).text();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...