日期:2014-05-16 浏览次数:20458 次
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>李战《悟透JavaScript》 精彩代码节选</title>
</head>
<body>
<script type ='text/javascript'>
function Class(){
var aDefine = arguments[arguments.length - 1];//最后一个参数是类定义
if (!aDefine)
return;
//基类为自定义的object或者是第一个参数的类
var aBase = arguments.length > 1 ? arguments[0] : object; //解析基类
function prototype_(){
};//构造prototype的临时函数,用于挂接原型链
prototype_.prototype = aBase.prototype;
var aPrototype = new prototype_();
//复制类定义到aPrototype,后面以它为原型对象
for (var member in aDefine) {
//构造函数不用复制
if (member != "Create") {
aPrototype[member] = aDefine[member];
}
}
//根据是否继承特殊属性和性能情况,可分别注释掉下列的语句
if (aDefine.toString != Object.prototype.toString)
aPrototype.toString = aDefine.toString;
if (aDefine.toLocaleString != Object.prototype.toLocaleString)
aPrototype.toLocaleString = aDefine.toLocaleString;
if (aDefine.valueOf != Object.prototype.valueOf)
aPrototype.valueOf = aDefine.valueOf;
if (aDefine.Create) {
//调用本身的构造函数,自定义为Create(注意它是一个函数,并没被执行)
var aType = aDefine.Create;
}
else {
//本例中好像没用到
aType = function(){
this.base.apply(this, arguments);
};
}
//aType并不是实例化的对象,而是自定义的构造函数(虽然函数也是对象)
aType.prototype = aPrototype;
//设置类型关系,便于追溯继承关系
aType.Base = aBase;
//为本类对象扩展一个Type属性,主要是为了作类型识别,实现instanceof
aType.prototype.Type = aType;
//返回构造函数作为类
return aType;
};
//根类object定义,主要是给那些没有显式定义基类的使用
function object(){
};
//判断对象是否属于某类型,类似于instanceof
object.prototype.isA = function(aType){
var self = this.Type;
while (self) {
if (self == aType) {
return true;
}
self = self.Base;
};
return false;
};
//调用基类构造函数
//这个版本主要是为了兼容不支持caller属性的Opera浏览器
object.prototype.base = function(){
//获取当前对象的基类
var Base = this.Type.Base;
//若基类己没有基类
if (!Base.Base) {
//则直接调用基类构造函数
Base.apply(this, arguments);
}
else {
//先覆写this.base
this.base = MakeBase(Base);
//再调用基类构造函数
Base.apply(this, arguments);
//删除覆写的base属性
delete this.base;
};
function MakeBase(Type){
var Base = Type.Base;
if (!Base.Base)
return Base;
return function(){
this.base = MakeBase(Base);
Base.apply(this, arguments);
};
};
}
//不支持Opera
object.pr