javascript动态原型方法的多继承实现

来源:互联网 发布:阿里云部署html 编辑:程序博客网 时间:2024/06/05 10:38
<script type="text/javascript">
function MultiExtend(subClass,superClass){
//含有三个以上参数,表明要继承的具体方法
if(arguments[2]){
for(var i=2,len=arguments.length;i<len;i++){
subClass.prototype[arguments[i]] = superClass.prototype[arguments[i]];
}
}else{
for(methodName in superClass.prototype){
if(!subClass.prototype[methodName]){
subClass.prototype[methodName] = superClass.prototype[methodName];
}
}
}
}


function SuperA(){
if (typeof SuperA._initialized == "undefined") {
SuperA.prototype.HelloA = function(){
alert('HelloA');
}
SuperA._initialized = true;
}
}


function SuperB(){
if (typeof SuperB._initialized == "undefined") {
SuperB.prototype.HelloB = function(){
alert('HelloB');
}
SuperB._initialized = true;
}
}


function SuperC(){
if (typeof SuperC._initialized == "undefined") {
//这样如果没初始化过父类就初始化一次
if (typeof SuperA._initialized == "undefined") SuperA.call(this);
if (typeof SuperB._initialized == "undefined") SuperB.call(this);
//可以实现多继承
MultiExtend(SuperC,SuperA);
MultiExtend(SuperC,SuperB);
SuperC.prototype.HelloC = function(){
alert('HelloC');
}
SuperC._initialized = true;
}
}
var sc = new SuperC();
sc.HelloA();
sc.HelloB();
sc.HelloC();

</script>

一、使用动态原型方法创建类的好处:

1.利用prototype创建方法,可以确保方法只实现一次,减少内存占用

2.可以使用在类内部定义的私有变量,如果使用原型模式创建则只能将私有变量公开

二、使用MultiExtend方法可以实现对多个类的继承,主要用于实现类似c#语言一样实现多个接口继承

原创粉丝点击