基本上,你可以這樣做:
(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