从/与其他非Backbone对象扩展Backbone.Model

时间:2013-02-08 15:17:54

标签: javascript inheritance backbone.js underscore.js

我想要实现的是使用Backbone.Model或其他方法扩展先前定义的类,无论哪种方法效果最好。基本上我的代码看起来像这样:

var SomeObject = function() {};
SomeObject.CLASS_ATTRIBUTE = 'something';
SomeObject.prototype.aFunction = function() { return Math.E; };
SomeObject.prototype.attrB = 'wat';

var SomeModel = Backbone.Model.extend({});

此时,如何使用SomeModel(或相反的方式)扩展SomeObject以包含CLASS_ATTRIBUTE以及aFunctionattrB作为Model属性而不失去Backbone.Model能力?

感谢您的回答!

2 个答案:

答案 0 :(得分:0)

如果SomeObject被定义为:

var SomeObject = {
  CLASS_ATTRIBUTE: 'something',
  aFunction: function () { return MATH.E; },
  attrB: 'wat'
}

然后

var SomeModel = Backbone.Model.extend({
 // ...
});

_.extend(SomeModel.prototype, SomeObject);

会做你需要的东西

答案 1 :(得分:0)

延伸是什么意思?

  1. 您想合并您的物品吗?
  2. 您是否希望向SomeModel添加自定义“方法”?
  3. 您是否希望创建一个同时包含SomeModelSomeObject的方法和属性的新对象?

  4. JSFiddle


    var SomeObject = function() {};
    SomeObject.CLASS_ATTRIBUTE = 'something';
    SomeObject.prototype.aFunction = function() { return Math.E; };
    SomeObject.prototype.attrB = 'wat';
    var SomeModel = Backbone.Model.extend({});
    
    // Merging instances of objects
    var newSomeObject = new SomeObject(),
        newSomeModel = new SomeModel(),
        mergedObjects = $.extend(true, newSomeModel, newSomeModel);
    
    console.log(mergedObjects);
    
    // Prototyping
    var mergedProto = $.extend(true, SomeModel.prototype, SomeObject.prototype);
    console.log(mergedProto);
    
    //factory
    var myMergefactory = function() {
        var ret = $.extend(true, SomeModel.prototype, SomeObject.prototype);
        return ret;
    }
    

    作为一个说明,这也是有效的......

    var SomeModel = Backbone.Model.extend({});
    SomeModel.CLASS_ATTRIBUTE = 'something';
    SomeModel.prototype.aFunction = function() { return Math.E; };
    SomeModel.prototype.attrB = 'wat';
    

    或者这......

    var SomeModel = Backbone.Model.extend({
        initialize: function (params) {
            $.extend(true, this, params.obj);
        }
    });
    var mObj = new SomeModel({obj: new SomeObject()});