5

我试图扩展骨干集合,第一种方式是我在声明中做 new,第二种方式是我先声明,然后创建一个新实例。是做第一个错,有什么区别?

var AppointmentList = new Backbone.Collection.extend({
  model: Appointment
});

var AppointmentList = Backbone.Collection.extend({
  model: Appointment
});

var aptlist = new AppointmentList();
4

1 回答 1

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,那么 thevar parent = this将引用扩展对象,但如果您不使用newthenvar parent = this将引用Backbone.Collection并且由于您只能调用.apply函数,因此代码将在此处中断:

child = function(){ return parent.apply(this, arguments); };

parent将是一个对象。Backbone.Collection是一个函数

于 2013-02-10T10:34:15.660 回答