2012-12-09 39 views
1

我試圖在Javascript中將現有對象重寫爲模塊。下面是我試圖改寫作爲一個模塊的代碼:以Javascript創建和使用模塊

var Queue = {}; 
Queue.prototype = { 
    add: function(x) { 
     this.data.push(x); 
    }, 
    remove: function() { 
     return this.data.shift(); 
    } 
}; 
Queue.create = function() { 
    var q = Object.create(Queue.prototype); 
    q.data = []; 
    return q; 
};   

這是我在做一個模塊的嘗試:

var Queue = (function() { 

    var Queue = function() {}; 

    // prototype 
    Queue.prototype = { 
     add: function(x) { 
      this.data.push(x); 
     }, 
     remove: function() { 
      return this.data.shift(); 
     } 
    }; 

    Queue.create = function() { 
     var q = Object.create(Queue.prototype); 
     q.data = []; 
     return q; 
    }; 


    return Queue; 
})(); 

這是正確的?如果是這樣,我如何在我的js代碼中的其他函數或區域中調用它。我感謝所有幫助!

+0

@IHateLazy,我忘了將它更改爲隊列,我的錯誤 –

回答

1

這似乎有點毫無意義有一個空的構造函數,那麼作爲有效利用對構造函數屬性的構造函數。

爲什麼不趁構造...

var Queue = (function() { 

    var Queue = function() { 
     if (!(this instanceof Queue)) 
      return new Queue(); 

     this.data = []; 
    }; 

    Queue.prototype = { 
     add: function(x) { 
      this.data.push(x); 
     }, 
     remove: function() { 
      return this.data.shift(); 
     } 
    }; 

    return Queue; 
})(); 

或者,如果你喜歡使用Object.create,我應該這樣做,而不是:

var Queue = (function() { 

    var Queue = function() { 
     var o = Object.create(proto); 

     o.data = []; 

     return o; 
    }; 

    var proto = { 
     add: function(x) { 
      this.data.push(x); 
     }, 
     remove: function() { 
      return this.data.shift(); 
     } 
    }; 

    return Queue; 
})(); 

在這兩種情況下, ,您只需使用Queue即可創建新對象。

var q = Queue(); 

從技術上講,第一個應該使用new Queue(),但它具有instanceof測試,讓new被省略。

+0

感謝您的幫助!並感謝剛剛跳過'Object.create'的提示 –