2

在此处输入图像描述

最近,我遇到了一个问题,即如何jQuery既作为函数又作为对象。使之成为可能的是,它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 的 Collection 或数据库表。

4

1 回答 1

1

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
于 2012-04-13T12:41:24.677 回答