jQuery dollar sign ($) as function argument?

后端 未结 4 1224
梦毁少年i
梦毁少年i 2020-11-27 13:09

I understand JavaScript closures, and I\'ve seen this done in native JS:

(function () {
  // all JS code here
})();

But, what does adding t

4条回答
  •  情书的邮戳
    2020-11-27 14:05

    There are two reasons to pass jQuery into a closure in this way.

    By far the most significant one is that it makes your code work on pages which use jQuery's "no conflict" mode, which allows the use of jQuery alongside other libraries which want control over the $ global. For this reason, the (function($) { ... })(jQuery) technique is strongly recommended when writing jQuery plugins.

    The secondary reason is that it makes $ a local variable in the scope of the self-executing function and local variable access is (marginally) faster than global variable access. Personally, I don't consider this a very compelling reason — I can't imagine a scenario in which the overhead of using jQuery rather than DOM methods would be acceptable, but that of accessing jQuery as a global variable wouldn't. :-)

    I'd say that the best reason to use this technique when not writing a plugin is for consistency — you're less likely to forget to do it when it is important if you're in the habit of doing it when it isn't. Besides, you never know when you'll have the opportunity to recycle code!

提交回复
热议问题