简体   繁体   English

将属性/方法增强到数组?

[英]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 . 最近,我遇到一个有关jQuery如何既充当函数又充当对象的问题 the thing that made it possible was that jQuery was actually a function (hence the $() ) that was attached with properties (like $.each() ). 使之成为可能的是jQuery实际上是一个附加了属性(例如$.each() )的函数(因此为$() $.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. 除此之外,我不想弄乱实际的Array原型的东西。 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. 我正在制作的模型与Backbone.js的模型不同,后者是数据的单位。 It's more synonymous to Backbone.js' Collection, or a Database table. 它是Backbone.js的Collection或Database表的同义词。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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