javascript面向对象包装类Class封装类库剖析(4)


functionF(){};
F.prototype=superCtor.prototype;
ctor.prototype=newF();
ctor.prototype.constructor=ctor;


同样的,除最后一个参数是当前类的方法声明,其它参数均做为继承父类,需要循环继承,但当这里处理的相对比较简单,没涉及到覆盖。你可以自己动手添加。

复制代码 代码如下:


varClass=(function(){
/**
*Inheritsfunction.(node.js)
*
*@paramctorsubclass'sconstructor.
*@paramsuperctorsuperclass'sconstructor.
*/
varinherits=function(ctor,superCtor){
//显式的指定父类
ctor.super_=superCtor;
//ECMAScript5原型式继承并解除引用
if(Object.create){
ctor.prototype=Object.create(superCtor.prototype,{
constructor:{
value:ctor,
enumerable:false,
writable:true,
configurable:true
}
});
}else{
//无Object.create方法的平稳退化
functionF(){};
F.prototype=superCtor.prototype;
ctor.prototype=newF();
ctor.prototype.constructor=ctor;
}
};
/**
*Classfunction.
*/
returnfunction(){
//最后一个参数是新类方法、属性和构造函数声明
varsubClazz=arguments[arguments.length-1]||function(){};
//initialize是构造函数,否构造函数就是一个空函数
varfn=subClazz.initialize==null?function(){}:subClazz.initialize;
//继承除最一个参数以的类,多继承,也可以用作扩展方法
for(varindex=0;index<arguments.length-1;index++){
inherits(fn,arguments[index]);
}
//实现新类的方法
for(varpropinsubClazz){
if(prop=="initialize"){
continue;
}
fn.prototype[prop]=subClazz[prop];
}
returnfn;
}
})();


看下面实例:

复制代码 代码如下:


/**
*ThedefinitionofCatClass.
*/
varCat=Class({
/**
*Constructor.
*
*@paramnameCat'sname
*/
initialize:function(name){
this.name=name;
},
/**
*Eatfunction.
*/
eat:function(){
alert(this.name+"iseatingfish.");
}
});
/**
*ThedefinitionofBlackCatClass.
*/
varBlackCat=Class(Cat,{
/**
*Constructor.
*
*@paramnameCat'sname.
*@paramageCat'sage.
*/
initialize:function(name,age){
//calltheconstructorofsuperclass.
BlackCat.super_.call(this,name);
this.age=age;
},
/**
*Eatfunction.
*/
eat:function(){
alert(this.name+"("+this.age+")iseatingdog.");
}
});
/**
*ThedefinitionofBlackFatCatClass.
*/
varBlackFatCat=Class(BlackCat,{
/**
*Constructor.
*
*@paramnameCat'sname.
*@paramageCat'sage.
*@paramweightCat'sweight.
*/
initialize:function(name,age,weight){
//calltheconstructorofsuperclass.
BlackFatCat.super_.call(this,name,age);
this.weight=weight;
},
/**
*Eatfunction.
*/
eat:function(){
alert(this.name+"("+this.age+")iseatingdog.Myweight:"+this.weight);
}
});
/**
*ThedefinitionofDogClass.
*/
varDog=Class({});
varcat=newBlackFatCat("John",24,"100kg");
cat.eat();
//true
alert(catinstanceofCat);
//true
alert(catinstanceofBlackCat);
//true
alert(catinstanceofBlackFatCat);
//true
alert(cat.constructor===BlackFatCat);
//false
alert(catinstanceofDog);


四、mootools类库的Class
源码解析可以看这里:
看具体用法:
a、新建一个类

复制代码 代码如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wddgyf.html