【问题标题】:Module Pattern - why is JQuery passed in as a parameter?模块模式 - 为什么将 JQuery 作为参数传入?
【发布时间】:2012-05-05 00:19:04
【问题描述】:

我想我了解模块模式,但是为什么有些示例将 JQuery 作为这样的参数传入:

Namespace.AppName = (function ($) {
     // Code Here
})(jQuery); 

如果我不传入 JQuery,我仍然可以通过在模块内调用 $() 来很好地使用 Jquery 库。那么为什么有些人会这样做呢?

【问题讨论】:

标签: javascript jquery


【解决方案1】:

为了使用 $ '安全'。大多数开发人员更喜欢使用 '$' 而不是 jQuery。

使用$作为全局时,可能会与其他JS库冲突。

【讨论】:

    【解决方案2】:

    这是为了确保您的命名空间/作用域使用 $ 作为 jQuery 而不是其他 JS 库,如 Prototype,它也使用 $。

    【讨论】:

      【解决方案3】:

      这样你就可以使用 $ 作为 jQuery 的快捷方式。如果你不这样封装,它有时会与其他库发生冲突。

      【讨论】:

        【解决方案4】:

        这里的想法是将jQuery 作为$ 传递给内部函数,确保$ 是jQuery。这通常用于保护使用 $ 的代码,尤其是在使用 jQuery 以及其他使用 $ 的库(如 mootools)时。


        例如,如果您在 <head> 中有此代码

        <!--load jQuery-->
        <script src="jquery.js"></script>
        
        <script>
            //"$" is jQuery
            //"jQuery" is jQuery 
        </script>
        
        <!--load another library-->
        <script src="anotherlibrary.js"></script>
        
        <script>
            //"$" is the other library
            //"jQuery" is jQuery 
        
            //out here, jQuery code that uses "$" breaks
        
            (function($){
                //"$" is jQuery
                //"jQuery" is jQuery (from the outside scope)
        
                //in here, jquery code that uses "$" is safe
        
            }(jQuery));
        
        </script>
        

        【讨论】:

        • "$" 是 anotherlibrary.js 将 $ 定义为全局时的另一个库。我认为
        猜你喜欢
        • 1970-01-01
        • 2018-01-08
        • 1970-01-01
        • 1970-01-01
        • 2019-11-16
        • 2018-09-28
        • 2023-03-23
        • 2018-03-16
        • 2014-01-12
        相关资源
        最近更新 更多