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
549 views
in Technique[技术] by (71.8m points)

jquery - Javascript wrapping code inside anonymous function

I need help understanding this pattern for jQuery plugin authoring. Can somebody explain this simple bit of code for me?

(function($) { /* Code here */ })(jQuery);

I know this is to avoid conflict with different plugins using the same $ character but somehow cannot get around my head to understand how it works. What relation does the parameter $ has to the jQuery object that got parsed in?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Let's break this down:

(function($) { /* Code here */ })(jQuery);

First, the construct:

(function() {})();

creates an immediately executed function expression (often called IIFE). This is a function that is executed immediately rather than defined now, but called later. It is essentially an anonymous (unnamed) function that is defined and then executed right away.

Then, passing jQuery to it like this:

(function() {})(jQuery);

passes jQuery as the first argument to that immediately executed function. Then, naming that first argument as $ defines that symbol inside the function to correspond to the first argument that is passed.

(function($) {})(jQuery);

which in expanded form looks like this:

(function($) {
    // you can use $ here to refer to jQuery
})(jQuery);

There a couple nice thing about this for jQuery plugin authors:

  1. The IIFE creates a local function context so you can have variables which are "global" for your plug-in, but are not actually global variables and thus don't pollute or conflict with the actual global variable namespace.

  2. You can program with $ for jQuery, whether or not the host program actually has that defined for jQuery because you've defined $ locally within your function.


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

...