您的位置:首页 > 其它

【原创】backbone0.9.2源码解析之extend

2012-11-27 15:57 579 查看
最近看了一下backbone的源代码,总的来说,对于MVC而言,写的真的挺不错的,但是如果说企业应用呢?个人觉得维护成本比较高。

源码主要是是写了类,Model,View,Collection,Router,通过继承这些类,实现自己的应用需求,所以说对于继承这块,我将源代码解析出来。

Model.extend = Collection.extend = Router.extend = View.extend = extend;


依旧看一下结构图:



图中红色图块的child是继承后的子类(是一个构造器function),parent为父类(如:Backbone.Model),Surrogate为中间类(图中红色图块是它的实例,存放child的公用方法),

staticProps是child的静态属性(或者方法),protoProps是child所有实例的公用属性(或者方法)

以下是源代码(附中文注释):

// Helpers
// -------

// Helper function to correctly set up the prototype chain, for subclasses.
// Similar to `goog.inherits`, but uses a hash of prototype properties and
// class properties to be extended.
// extend用来实现继承,返回一个javascript类,也就是一个构造器function(父类叫做parent,子类叫做child)
// 参数protoProps对象中的属性是所有child实例的公用方法
// 参数staticProps对象中的属性是child类的静态属性
var extend = function(protoProps, staticProps) {
var parent = this;
var child;

// The constructor function for the new subclass is either defined by you
// (the "constructor" property in your `extend` definition), or defaulted
// by us to simply call the parent's constructor.
// 如果定义了protoProps,且protoProps有constructor属性(function)
// 那么protoProps.constructor将作为子类的构造器
// 否则,会定义一个构造器,且构造器里调用了父类的构造函数
if (protoProps && _.has(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {
child = function(){ parent.apply(this, arguments); };
}

// Add static properties to the constructor function, if supplied.
// 将静态属性staticProps以及parent上的类属性添加到child上作为类属性
_.extend(child, parent, staticProps);

// Set the prototype chain to inherit from `parent`, without calling
// `parent`'s constructor function.
// 通过中间函数Surrogate,将原型链连接起来
// this.constructor = child; 这一步很重要,用来说明之后child实例的构造器是谁?显然是child
var Surrogate = function(){ this.constructor = child; };
// 继承父类的所有公用方法
Surrogate.prototype = parent.prototype;
// 连接原型链
child.prototype = new Surrogate;

// Add prototype properties (instance properties) to the subclass,
// if supplied.
// 将protoProps对象中的方法放入child.prototype中,作为所有child的实例的公用方法
if (protoProps) _.extend(child.prototype, protoProps);

// Set a convenience property in case the parent's prototype is needed
// later.
// 指明child类的父类是谁?
child.__super__ = parent.prototype;

// 返回生成的子类
return child;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: