2011.05.31
■[jQuery][JS] 名前空間の衝突を避けるしくみ noConflict()
jquery-1.6.1.js の noConflict() のところを読みました。そのメモです。
ロードするまでの window.jQuery、window.$ を退避しておき、必要に応じて、$ だけなら noConflict() を、$ と jQuery なら noConflict(true) を呼び出すことで、それらに戻します。関数 noConflict は現在の jQuery を戻り値で返すので、それを格納する変数が今回の jQuery オブジェクトであるという目印となります。複数バージョンの jQuery を読み込み使い分けることができます。
(function( window, undefined ) { ... var jQuery = (function() { // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, ... noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; },
名前空間の衝突の可能性は、$ や jQuery に限ったことではありません。ChiperSoft/Timed - GitHub では、"Timed" に対し、同様の noConflict 関数が定義されています。
(function (context) { ... var oldTimed = context.Timed; Timed.noConflict = function () { context.Timed = oldTimed; return this; }; context.Timed = Timed; })(this);
こちらは underscore.js の例です。
// Save the previous value of the `_` variable. var previousUnderscore = root._; ... // Run Underscore.js in *noConflict* mode, returning the `_` variable to its // previous owner. Returns a reference to the Underscore object. _.noConflict = function() { root._ = previousUnderscore; return this; };
