js继承 Base类的源码解析
2024-05-06 14:16:17
供稿:网友
// timestamp: Tue, 01 May 2007 19:13:00
/*
base2.js - copyright 2007, Dean Edwards
http://www.opensource.org/licenses/mit-license
*/
// You know, writing a javascript library is awfully time consuming.
//////////////////// BEGIN: CLOSURE ////////////////////
// =========================================================================
// base2/Base.js
// =========================================================================
// version 1.1
var Base = function(){
// call this method from any other method to invoke that method's ancestor
};
Base.prototype = {
extend: function(source){
//参数大于一个时
if (arguments.length > 1) { // extending with a name/value pair
//获得proto的祖先
var ancestor = this[source];
var value = arguments[1];
//如果value(第二个参数)是function,并且祖先对象存在,在重载函数中调用base时
if (typeof value == "function" && ancestor && //bbase/b/.test(value)) {
// get the underlying method
var method = value;
// override
value = function(){
var previous = this.base;
this.base = ancestor;
//上溯到父类对象
var returnValue = method.apply(this, arguments);
this.base = previous;
return returnValue;
};
value.method = method;
value.ancestor = ancestor;
}
this[source] = value;
}
else
if (source) { // extending with an object literal 用一个对象列表来扩展
var extend = Base.prototype.extend;
/**
* 1.扩展原型方法和属性 2.
*/
//如果是扩展属于原型的方法或属性,先遍历其重载Object的3个方法
if (Base._prototyping) {
var key, i = 0, members = ["constructor", "toString", "valueOf"];
while (key = members[i++]) {
//如果是重载了这些方法
if (source[key] != Object.prototype[key]) {
/**
* 逐个扩展,用call的原因是要将extend的上下文改为要扩展的源this,
* 既是新建对象的父类对象
*/
extend.call(this, key, source[key]);
}
}
}
else
if (typeof this != "function") {
// if the object has a customised extend() method then use it
extend = this.extend || extend;
}
// copy each of the source object's properties to this object
for (key in source)
if (!Object.prototype[key]) {
extend.call(this, key, source[key]);
}
}
return this;
},
base: Base
};
Base.extend = function(_instance, _static){ // subclass
/**
* Base类原型的扩展别名,将这个当成一个方法调用
*/
var extend = Base.prototype.extend;
/**
* build the prototype,创建原型
* 设置原型标志
*/
Base._prototyping = true;
/**
* 创建一个Base的实例,初始化继承部分
* 继承方式大致还是以下方式
* function A(){}
* function B(){
* this.b=[];
* }
* A.prototype=new B();//A继承B的所有属性和方法
* 这种继承方式会有一个问题,B中声明的对象(如b)以prototype的形式