Reputation: 119867
recently, i came across a question of how jQuery
acts as both a function, as well as an object. the thing that made it possible was that jQuery
was actually a function (hence the $()
) that was attached with properties (like $.each()
).
now in my project, i would want to create a model (which technically is an array of stuff), add methods to it, and return it to a variable which will hold it. is it wise to do it like this? does it interfere with anything?
//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');
To add to that, I don't want to mess around with the actual Array
prototype stuff. I'm doing this for the currently created array.
the model i'm making is not like Backbone.js' model which is a unit of data. It's more synonymous to Backbone.js' Collection, or a Database table.
Upvotes: 2
Views: 269
Reputation: 10874
Something in that style might do, also never start a model as an array, always take a function (constructor) and a proper object they are more flexible for that.
var model = function(data) {
this.data = data;
};
model.prototype.getData = function() {
return this.data;
};
var mod = new model({foo:'foo'});
mod.getData().foo
Upvotes: 1