我在JS中使用以下模式:
var lib =
{
module_one:
{
init: function () {
...
}
},
module_two:
{
init: function () {
...
}
}
};
问题是,最好的添加方法是什么:
(function ($) {
...
})(jQuery);
我试图把它放在var lib周围,但那不起作用。在每个功能内部添加它,但似乎有点凌乱..?
是否有可能以某种方式将它添加到init:function($)?
关于jQuery的新功能,如果您对此模式有任何其他建议,请告诉我: - )
答案 0 :(得分:3)
基本上,你可以这样做:
(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引用,以便有人可以将其用作别名。顺便说一句,当您使用作用域函数时,您也可以切换到使用命名函数而不是匿名函数has several benefits。以上是更新后使用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;
})();