gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 09:02:00 24 4
gpt4 key购买 nike

是这个模式吗:

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com