Module 如何将noConflict添加到JS模块模式?
我在JS中使用以下模式:Module 如何将noConflict添加到JS模块模式?,module,design-patterns,jquery,Module,Design Patterns,Jquery,我在JS中使用以下模式: var lib = { module_one: { init: function () { ... } }, module_two: { init: function () { ... } } }; 问题是,最好的补充方式是什么: (function ($) { ... })(jQuery); 我试着把它放在var库周围,但那不起作
var lib =
{
module_one:
{
init: function () {
...
}
},
module_two:
{
init: function () {
...
}
}
};
问题是,最好的补充方式是什么:
(function ($) {
...
})(jQuery);
我试着把它放在var库周围,但那不起作用。在每个函数中添加它是有效的,但是看起来有点混乱
是否可以以某种方式将其添加到init:函数($)中
jQuery非常新,因此如果您对这种模式有任何其他建议,请告诉我:-)基本上,您可以这样做:
(function() {
var global, lib, oldlib;
// We call this anonymous scoping function directly, so we know that
// within it, `this` is the JavaScript global object. Grab a
// local reference to it so we can use it within functions that get
// called via dotted notation and so have different `this` values.
global = this;
// Remember any value that already exists for the `lib` property
// of the global
oldlib = global.lib;
// Define our lib, assigning it to a local variable
lib = {
/* ...your stuff as usual, plus: */
noConflict: function() {
global.lib = oldlib;
return lib;
}
};
// Publish our lib externally on the global object
global.lib = lib;
})();
…然后可以这样使用:
var alias = lib.noConflict();
下面是它的工作原理:
this
值作为名为global
的变量。这将是JavaScript全局对象,因为我们调用作用域函数的方式。(浏览器上的全局对象是window
,但不需要将其限制在浏览器上,因此可以通过这种方式获得global
)lib
属性所具有的任何旧值保存在名为oldlib
的作用域函数中的局部变量中lib
设置了新值noConflict
函数恢复lib
属性的早期值,并返回我们的lib引用,以便有人可以将其用作别名noConflict
使用命名函数
(function() {
var global, lib, oldlib;
// We call this anonymous scoping function directly, so we know that
// within it, `this` is the JavaScript global object. Grab a
// local reference to it so we can use it within functions that get
// called via dotted notation and so have different `this` values.
global = this;
// Remember any value that already exists for the `lib` property
// of the global
oldlib = global.lib;
// Define the functions for our lib. Because they're defined
// within our scoping function, they're completely private
function lib_noConflict() {
global.lib = oldlib;
return lib;
}
// Define our lib, publishing the functions we want to be public
lib = {
/* ...your stuff as usual, plus: */
noConflict: lib_noConflict
};
// Publish our lib externally on the global object
global.lib = lib;
})();
lib
是什么,一个全局变量?