Home  >  Article  >  Web Front-end  >  Javascript编程之继承实例汇总_javascript技巧

Javascript编程之继承实例汇总_javascript技巧

WBOY
WBOYOriginal
2016-05-16 15:29:18946browse

本文实例讲述了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

六、各种继承法的优缺点

希望本文所述对大家JavaScript程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn