L
L
lagaca2016-03-03 09:27:40
JavaScript
lagaca, 2016-03-03 09:27:40

Why (function($){…})(jQuery)?

Why is it customary to write:

(function($) {
  $.fn.mySimplePlugin = function(){
     // код плагина ...
     return this;
  };
})(jQuery);


But not:

$.fn.mySimplePlugin = function($){
     // код плагина ...
     return this;
  };


Google says that the first option will isolate the $ and allow this to be returned. But the other one does it too. But it's also shorter.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2016-03-03
@lagaca

The (function($){…})(jQuery) construct isolates the plugin's namespace. This is a guarantee that the plugin will not overwrite someone else's variable, for example.

O
OnYourLips, 2016-03-03
@OnYourLips

To shut up the holey scope model in JS.
In modern JS, this is not necessary: ​​modules and let fixed the problem.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question