backbone extend 源码分析

时间:2023-12-31 11:57:38
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); };
}
/*定义child是子类的构造器函数*/ _.extend(child, parent, staticProps);
/* 扩展 child的静态属性和方法,这里默认所有子类有extend静态方法,理解for(var i in function) */ var Surrogate = function(){ };
/* 在 new的时候重写constructor属性 */ Surrogate.prototype = parent.prototype;
/* 即使这里的constructor被污染了也没有关系,拿到父类prototype的所有方法 */ child.prototype = new Surrogate();
/*因为 prototype之后 child.prototype.constructor指向child ,这里必须是new一下 ,克隆child对象 */ if (protoProps) _.extend(child.prototype, protoProps);
/*最后一步 添加子类的方法到 child的prototype上*/ child.__super__ = parent.prototype; return child;
/*返回子类构造器函数*/
}; Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
/*给Backbone.Model,Backbone.Collection, Backbone.Router,Backbone.View添加extend静态方法。 函数是对象,此处引用*/