javascript - 传递 jQuery 或不同全局的模块模式

标签 javascript module-pattern

是这个模式吗:

// Global module
var myModule = (function ( jQ, _ ) {

    function privateMethod1(){
        jQ(".container").html("test");
    }

    function privateMethod2(){
      console.log( _.min([10, 5, 100, 2, 1000]) );
    }

    return{
        publicMethod: function(){
            privateMethod1();                
        }            
    };

// Pull in jQuery and Underscore
}( jQuery, _ ));

myModule.publicMethod();  

我不明白传递全局的目的是什么,如果它是全局的?

让 jQuery 或其他全局“更接近”的原型(prototype)链离得不是那么远,这样会更有效率吗?

如果有人想使用

jQ

指的是 jQuery

为什么不这样做

var jQ = jQuery

在他/她想要使用它的范围内。

最佳答案

这样做的一个原因是如果您在使用 jQuery noconflict 的页面上有多个版本的 jQuery ,您可以隔离此代码,使其不必了解或担心它。您只需传递正确的版本即可。如果您想使用 $ 简写,这也可以很好地防止与其他库发生冲突,例如也使用 $ 符号的 Mootools。

总的来说,虽然我同意你的观点,但它似乎并不是特别有用。

更新

这实际上似乎就是这种特殊用法的原因。来自 source you linked :

Here, we’ve wrapped our plugin logic in an anonymous function. To ensure that our use of the $ sign as a shorthand creates no conflicts between jQuery and other JavaScript libraries, we simply pass it to this closure, which maps it to the dollar sign.

还有

This variation of the pattern demonstrates how globals (e.g jQuery, Underscore) can be passed in as arguments to our module's anonymous function. This effectively allows us to import them and locally alias them as we wish.

因此,它用作一个人为示例,以表明如果您喜欢较短的名称,可以为全局变量添加别名。

关于javascript - 传递 jQuery 或不同全局的模块模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17621256/

相关文章:

javascript - Javascript模块中的变量在外面可见吗?

javascript - Google map v3 - 以英里为单位的可视 map 半径

javascript - 使用 ES6 箭头函数 Babelifying JavaScript 模块模式

javascript - 以不显眼的方式更好地组织和执行 JavaScript - 自执行匿名函数

javascript - IIFE 模块内部的 JSHint "is already defined"错误真的有效吗?

javascript - javascript中包含特殊字符的多行字符串?

javascript - 未捕获的类型错误 : Cannot read property 'ca' of null when dragging Google Map

javascript - 使用次要和主要刻度 d3js 创建波德图

javascript - (揭示)模块模式、公共(public)变量和返回语句

JavaScript 使用模块模式创建类