Javascript继承汇总


本文是我在看完《Javascript 王者归来》后的整理总结,文章详细章节在 第21章 P537

继承一般要实现以下三层含义:

1)子类实例可以共享父类的方法;

2)子类可以覆盖父类的方法或者扩展新的方法;

3)子类和父类都是子类实例的类型。

 

一、构造继承法

子类中调用父类的构造函数来维护的,该继承法能实现多重继承,但只能继承父类的共有方法,无法继承静态方法,而且不能用instanceof来验证实例。 

function a(){
    this.say=function(){
    alert("happy new year!");
    }
}

function b(){
    a.apply(this,arguments);
}

a.prototype.fuck=function(){
    alert("%^&%^&%&^%&");
}

var oB=new b();
alert(oB instanceof a);// false
oB.say();              // happy new year
oB.fuck();             // 读不到

 

二、原型继承法/经典继承法

该继承法是通过复制已经存在的原型对象来实现行为重用,让对象实例共享原型对象的属性。支持多重继承,继承原型静态方法,能用instanceof来验证实例。 

function a(){
 this.say=function(){
 alert("happy new year!");
 }
}

function b(){}

a.prototype.fuck=function(){
    alert("%^&%^&%&^%&");
}


a.prototype.z=123;
b.prototype=new a();

var oB=new b();
alert(oB instanceof a); // true
alert(oB.z);            // 123
oB.say();               // happy new year
oB.fuck();              // %^&%^&%&^%&


三、实例继承法/寄生构造函数模式

构造法不能继承类型的静态方法,原型继承得不完善(某些核心对象的不可枚举方法不能继承),而实例继承法能对原生核心对象或者DOM对象进行继承,它通过在类型中构造对象并返回的办法来实现继承,因此instanceof验证会是false,不支持多重继承。

function a(){
 var oA=new Array();
 oA.say=function(){
     alert("hello A!");
 }
 return oA;
}

var obj=new a();
alert(obj instanceof a); // false
obj.say();

四、拷贝继承法

该方法通过拷贝基类对象的所有可枚举属性和方法来模拟继承,因此它可以模拟多继承,但不能枚举的就无法继承;它可以继承父类的静态方法;

function a(){
    this.num=123;
    this.say=function(){
    alert("happy new year!");
    }
}

function b(){
    this.extends=function(obj){
        for(each in obj){
            this[each]=obj[each];
        }
    }
}

var oB=new b();
oB.extends(new a());

alert(oB instanceof a); // false
alert(oB.num);          // 123
oB.say();               // happy new year


五、混合继承法

顾名思义就是把上面几种继承法综合起来,取长补短,让继承更完善。常见的有 构造+原型继承:伪经典继承

function a(){
    this.num=123;
    this.say=function(){
    alert("happy new year!");
    }
}

function b(){
    a.apply(this);
}

b.prototype=new a();
b.prototype.z=123;

var oB=new b();
alert(oB instanceof a); // true
alert(oB.num);          // 123
oB.say();               // happy new year



六、各种继承法的优缺点




本文转载自:http://blog.sina.com.cn/s/blog_74d6cedd0100z7z3.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值