Reputation: 755
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?
Upvotes: 3
Views: 755
Reputation: 370789
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.
Upvotes: 1