[英]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:有一种非常常见的技术来编写$
而不是jQuery
并将其包装在一个函数中,如下所示:
(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:将无法工作,因为您是在该本地范围内操作,而不是在window
范围内操作,并且它将无法找到该函数,例如:
(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:要么将函数显式分配给window
:
(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.这与 jQuery 没有任何关系 - 在任何 IIFE 或任何不在顶层的块中都可以看到相同类型的行为(和解决方案)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.