第一种:冒充方式继承

冒充方式其实是程序员为了实现继承而采取trick

 

/* ClassA 的原始定义 */
function ClassA(sColor) {
    
this.color = sColor;
    
this.sayColor = function(){
        alert(
this.color);
    }

}

/* ClassB 定义 */
function ClassB(sColor, sName) {
    
this.newMethod = ClassA;
    
this.newMethod(sColor);
    
delete this.newMethod;
    
this.name = sName;
    
this.sayName = function() {
        alert(
this.name);
    }

}

/*ClassB 也可以如下定义 */
/*使用call,或者apply方法 */
function ClassB(sColor, sName) {
    ClassA.call(
this,sColor);  /* 或者 ClassA.apply(this,arguments); */
    
this.name = sName;
    
this.sayName = function() {
        alert(
this.name);
    }

}

冒充方式的缺点就是必须使用构造函数

第二种:原型链

//基类   
function ClassA() { }   
ClassA.prototype.color 
= "red";    
ClassA.prototype.sayColor 
= function() {   
    alert(
this.color);   
}
   
//子类   
function ClassB() {        
}
   
//可以获得CLassA的所有属性与方法但又不用一一将将它们赋予ClassB的prototype属性 
ClassB.prototype = new ClassA();   
//定义新属性与方法   
ClassB.prototype.name = "";   
ClassB.prototype.sayName 
= function() {   
    alert(
this.name);   
}
   

这种方法实现类继承很是灵活,实用.不过原型链的不足就是它不支持多重继承,并且构造函数也不能带有参数.
   总结以上,对象冒充的主要问题是必须使用构造函数方式,这不是最好的选择,但是使用原型链就无法使用带参数的构造函数了。所以,现在介绍一种两全其美的方式------混合方式.
   以前,我们创建类的最好方式是用构造函数方式定义属性,用原型方式定义方法。同样的这种方式也适用于继承机制,用对象冒充继承构造函数的属性,用原型链继承prototype对象的方法.

第三种:混合法(冒充法+原型链法)

function ClassA(sColor) {   
    
this.color = sColor;   
}
     
ClassA.prototype.sayColor 
= function() {   
    alert(
this.color);   
}
    
function ClassB() {   
    ClassA.call(
this, sColor);   //对象冒充方式  继承属性   
    this.name = sName;   
}
    
ClassB.prototype 
= new ClassA();  //原型链方式 继承方法   
ClassB.prototype.sayName = function() {   
    alert(
this.name);   
}
   

 

 

posted on 2008-07-24 16:19  SurfInGis  阅读(384)  评论(0编辑  收藏  举报