我想要实现的是使用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
以及aFunction
和attrB
作为Model属性而不失去Backbone.Model
能力?
感谢您的回答!
答案 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)
延伸是什么意思?
SomeModel
添加自定义“方法”?SomeModel
和SomeObject
的方法和属性的新对象?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()});