2010-09-08 85 views
1

我用下面的方式在我的JS:如何將noConflict添加到JS模塊模式?

var lib = 
{ 
    module_one: 
    { 
     init: function() { 
      ... 
     } 
    }, 
    module_two: 
    { 
     init: function() { 
      ... 
     } 
    } 
}; 

的問題是,什麼最好的方式來增加:

(function ($) {   
    ... 
})(jQuery); 

我試圖把它掛在了var LIB,但沒有工作。要在每個函數內部添加它,但似乎有點凌亂..?

是否有可能以某種方式將它添加到init:function($)?

相當新的jQuery的,所以如果你有解決這個模式的任何其他建議,讓我知道:-)

+0

什麼是'lib'意圖是一個全局變量? – 2010-09-08 10:05:12

回答

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(); 

這裏是如何工作的:

  1. 我們定義了一個範圍函數,然後立即調用它。
  2. 在範圍函數中,我們獲取this值作爲變量global。由於我們調用範圍函數的方式,這將成爲JavaScript全局對象。 (瀏覽器上的全局對象是window,但不需要限制瀏覽器,因此以這種方式獲得global)。
  3. 我們要做的第一件事就是保存全局對象的lib屬性的任何舊值,在我們的作用域函數oldlib的局部變量中。
  4. 我們爲lib設置了新值。
  5. 我們的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; 
})();