基本上,你可以这样做:
(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;
})();
什么是'lib'意图是一个全局变量? – 2010-09-08 10:05:12