简体   繁体   中英

why is (jQuery) after function closing bracket

I'm working with a Magento site. I'm running into an issue getting Magento's prototype.js to play nice with jQuery. I've read that all of my jQuery needs to be using jQuery.noConflict(); which I've done but am still having some issues. I have seen that some functions closing brackets are followed by (jQuery).

I'm wondering what this is for and if I need to change it to (jQuery.noConflict())?

There is no need to change (jQuery) to (jQuery.noConflict()) as long as jQuery.noConflict() is called before that point (and after the JQuery library is included).

As you know, when you are using jQuery in no-conflict mode, you should use jQuery instead of $ .

But you can use $ instead of jQuery in code placed inside an immediately invoked function expression (IIFE), like this:

(function($) {
    // Code here can use $, instead of jQuery.
})(jQuery);

An IIFE is where you define an anonymous function and immediately call it. In the code above, the jQuery object is passed as an argument to the anonymous function, and since the parameter is named $ , $ represents the jQuery object inside the function.

Also, the jQuery object is passed as the first parameter to the callback function for the document-ready event, so you can do the following:

jQuery(function($) {
    // Code here can use $, instead of jQuery.
});

Which is the same as:

jQuery(document).ready(function($) {
    // Code here can use $, instead of jQuery.
});

Just be aware that variables declared with var inside an IIFE are not global. This is often a good thing, and is another reason to use IIFEs. If you do want to declare a global variable inside an IIFE, you should refer to it as a property of the window object.

<script type="text/javascript">
var a = 1; // This is a global variable.
(function($) {
    var b = 2; // This is NOT a global variable.
    window.c = 3; // This is a global variable.
})(jQuery);
<script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM