简体   繁体   中英

Augmenting properties/methods to an array?

在此处输入图片说明

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM