简体   繁体   中英

How to use the dollar sign for jQuery without wrapping inside an anonymous function?

There's a very common technique to write $ instead of jQuery and wrap it inside a function as such:

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

Now, the problem with this is that, you are inside a small, local scope and that's good, for the most part, but if you're trying to, say, call a function name dynamically by string-construction:

let dynamic_name = some_function_name; //but should be dynamic, duh
window[dynamic_name]();

Won't work because you're operating inside that local scope, not inside the window scope and it will not be able to find that function, example:

 (function($) { //If we put this outside of this scope, it works. function test() { console.log('test'); } let name = 'test'; window[name](); })(jQuery);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

This also means that if your script gets used as a library, your functions are not callable, because you're wrapping them inside an anonymous function.

Exactly how do you get around this?

Either assign the function to window explicitly:

 (function($) { window.test = function test() { console.log('test'); } let name = 'test'; window[name](); })(jQuery);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Or put the function in an object instead:

 (function($) { //If we put this outside of this scope, it works. const fns = { test() { console.log('test'); } }; let name = 'test'; fns[name](); })(jQuery);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

This doesn't really have anything to do with jQuery - the same sort of behavior (and solution) can be seen in any IIFE, or any block that's not on the top level.

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