我正试图通过创建自己的MVC库来深入研究javascript。我正在研究backbone.js源代码https://github.com/jashkenas/backbone/blob/master/backbone.js。
在backbone.js中定义集合时,应该将其分配给类似于以下var AppCollection = Backbone.Collection.extend({ model: BACKBONE_MODEL })的javascript变量
在内部,创建者使用下划线,并将prototype的Collection传递给下划线的_.extend()方法,比如这个_.extend(Collection.prototype, Events, {}),其中空对象参数驻留在我编写的示例中,作者在这里为Collection对象添加所有方法,即值为库中前面定义的模型对象的model键。
我很好奇,如何避免下划线依赖,并为集合添加自己的原型方法,特别是如何将带键model的对象传递到自己的Collection对象中?
这是我到目前为止所拥有的。
(function(Pigeon, root, factory) {
root[Pigeon] = factory();
} ('Pigeon', this, function() {
var Pigeon = {};
// Model
var Model = Pigeon.Model = function() {
this.attributes = {};
};
// Collection
var Collection = Pigeon.Collection = function(models) {
};
// View
Pigeon.View = {};
// Controller
Pigeon.Controller = {};
return Pigeon;
}));发布于 2016-01-24 06:30:32
为了防止对"_“的依赖,可以使用以下方法扩展对象或类,而不是"_.extend()”。
您可以使用Object.assign扩展原型。问题是,它不是完全支持所有的浏览器(我在看你的IE)。另一个选项是创建自己的扩展函数。您可以使用Object.keys(mixinClass)来完成此操作。
使用Object.assign:
function a() {
this.propOne = "one";
}
a.prototype.methodOne = function() {
document.write("<br/>I am methodOne from a");
}
function b() {
this.propTwo = "two";
}
b.prototype.methodTwo = function() {
document.write("<br/>I am methodTwo from b");
}
function assigned() {
// Call both "super" constructors (order can matter depending on your case)
a.call(this);
b.call(this);
}
// Assign other object properties to your object and set constructor
Object.assign(assigned.prototype, a.prototype, b.prototype);
assigned.constructor = assigned;
var x = new assigned();
document.write("<pre>I am assigned and I look like: \n" + JSON.stringify(x, 2, null) + "</pre>");
x.methodOne();
x.methodTwo();
使用自定义扩展函数:
function myExtend() {
var args = Array.prototype.slice.apply(arguments);
var target = args.shift();
var extended = {};
args.forEach(function(o) {
Object.keys(o).forEach(function(k) {
extended[k] = o[k];
});
});
Object.keys(extended).forEach(function(k) {
if (!target[k])
target[k] = extended[k];
});
}
function a() {
this.propOne = "one";
}
a.prototype.methodOne = function() {
document.write("<br/>I am methodOne from a");
}
function b() {
this.propTwo = "two";
}
b.prototype.methodTwo = function() {
document.write("<br/>I am methodTwo from b");
}
function assigned() {
a.call(this);
b.call(this);
}
myExtend(assigned.prototype, a.prototype, b.prototype);
assigned.constructor = assigned;
var x = new assigned();
document.write("<pre>I used myExtend and I look like: \n" + JSON.stringify(x, 2, null) + "</pre>");
x.methodOne();
x.methodTwo();
这个概念是一个混合体。您可以使用它来扩展简单对象或“混合”多个类,以创建具有多种类型方法的子类。不幸的是,这并不理想,因为对象实际上拥有"supers“属性和方法的副本,而不是使用引用。无论哪种方式,这都应该适用于您的用例。
https://stackoverflow.com/questions/34972643
复制相似问题