簡體   English   中英

如何在不包含匿名函數的情況下為 jQuery 使用美元符號?

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

有一種非常常見的技術來編寫$而不是jQuery並將其包裝在一個函數中,如下所示:

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

現在,問題在於,您在一個小的本地范圍內,這在大多數情況下是好的,但是如果您嘗試通過字符串構造動態調用函數名稱:

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

將無法工作,因為您是在該本地范圍內操作,而不是在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>

這也意味着如果您的腳本被用作庫,則您的函數不可調用,因為您將它們包裝在匿名函數中。

你如何解決這個問題?

要么將函數顯式分配給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>

或者將函數放在一個對象中:

 (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>

這與 jQuery 沒有任何關系 - 在任何 IIFE 或任何不在頂層的塊中都可以看到相同類型的行為(和解決方案)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM