2012-04-13 80 views
2

enter image description here增加數組的屬性/方法?

最近,我碰到a question of how jQuery acts as both a function, as well as an object。使得它成爲可能的原因是jQuery實際上是一個函數(因此是$()),它附有屬性(如$.each())。

現在在我的項目中,我想創建一個模型(技術上是一個東西的數組),並向它添加方法,並將其返回到一個將保存它的變量。這樣做是明智的嗎?它干擾什麼?

//i did it like this: 
function createModel(name){ 
    var model = internal.models[name] = []; 
    model.add = function(){..logic to add to the model..} 

    //more augmented methods here... 

    return model; 
} 

//create a model 
var myModel = createModel('test'); 

//then i can do add 
myModel.add('foo'); 

要補充的,我不想浪費時間與實際Array原型的東西。我正在爲當前創建的數組做這件事。


我製作的模型不像Backbone.js的模型,它是一個數據單元。它更像Backbone.js的集合或數據庫表的同義詞。

回答

1

該風格中的某些東西可能會這樣做,也從來沒有將模型作爲數組啓動,而是始終採用函數(構造函數)和適當的對象,因此它們更靈活。

var model = function(data) { 
    this.data = data; 
}; 

model.prototype.getData = function() { 
    return this.data; 
}; 

var mod = new model({foo:'foo'}); 

mod.getData().foo 
+0

更新了我的文章。實際上,代碼位於一個函數中,該函數返回新創建的模型以供參考以及操作。 – Joseph 2012-04-13 12:44:47