我试图扩展骨干集合,第一种方式我在声明中做了新的事情,在第二种方法中我首先声明然后我创建了一个新实例。做第一个错误,有什么区别?
var AppointmentList = new Backbone.Collection.extend({
model: Appointment
});
和
var AppointmentList = Backbone.Collection.extend({
model: Appointment
});
var aptlist = new AppointmentList();
答案 0 :(得分:8)
第一个将破解
var Appointment = Backbone.Model.extend({
defaults: {
"time": "0000",
"note": "This is an appointment"
}
});
var AppointmentList = new Backbone.Collection.extend({
model: Appointment
});
var aptlist = new AppointmentList();
在Backbone.js中我们有
var extend = function(protoProps, staticProps) {
var parent = this;
var child;
if (protoProps && _.has(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {
child = function(){ return parent.apply(this, arguments); };
}
_.extend(child, parent, staticProps);
var Surrogate = function(){ this.constructor = child; };
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate;
if (protoProps) _.extend(child.prototype, protoProps);
child.__super__ = parent.prototype;
return child;
};
如果使用new
运算符实例化Backbone.Collection.extend,则var parent = this
将引用extend对象,但如果不使用new
,则{{1 }}将引用var parent = this
,因为您只能在函数上调用Backbone.Collection
,代码将在此处中断:
.apply
child = function(){ return parent.apply(this, arguments); };
将是一个对象。 parent
是一个函数