2011-09-24 49 views
8

我想寫一個JS庫和處理這樣的:編寫JavaScript庫

var c1 = Module.Class(); 
c1.init(); 
var c1 = Module.Class(); 
c2.init(); 

和當然,C1和C2不能共享相同的變量。 我想我知道如何使用對象做到這一點,那就是:

var Module = { 

    Class = { 

     init = function(){ 
      ... 
     } 

    } 

} 

但問題是我不能有類的多個實例,如果我這樣寫。 所以我試圖達到同樣的功能,但我不認爲我做對了。

(function() { 

    var Module; 
    window.Module = Module = {}; 

    function Class(i) { 
     //How can "this" refer to Class instead of Module? 
     this.initial = i; 
    } 

    Class.prototype.execute = function() { 
     ... 
    } 

    //Public 
    Module.Class = Class; 

})(); 

我沒有線索,如果它甚至是可能的,但我接受其他方式建立此模塊的建議。 我不知道它是否也相關,但我在這個庫中使用jQuery。

回答

14

用法:

var c1 = Module.Class("c"); 
var c2 = Module.Class("a"); 
var n = c1.initial(); // equals 'c' 
c1.initial("s"); 
n = c1.initial(); // equals 's' 

模塊代碼:

(function(window) { 
    var Module = window.Module = {}; 
    var Class = Module.Class = function(initial) 
    { 
     return new Module.Class.fn.init(initial); 
    }; 
    Class.fn = Class.prototype = { 
     init: function(initial) { 
      this._initial = initial; 
     }, 
     initial: function(v){ 
      if (v !== undefined) { 
       this._initial = v; 
       return this; 
      } 
      return this._initial; 
     } 
    }; 
    Class.fn.init.prototype = Class.fn; 
})(window || this); 

這是使用JavaScript 「模塊」 設計模式;這與JavaScript庫(如jQuery)使用的設計模式相同。

這裏的 「模塊」 模式一個很好的教程: JavaScript Module Pattern: In-Depth

+1

完美!非常感謝你! –

+2

不客氣。 –