javascript继承

来源:互联网 发布:野火六大门派源码 编辑:程序博客网 时间:2024/06/07 10:07
  1. 类继承

    类继承也叫构造函数继承,其表现形式是在子类中执行父类的构造函数。实现本质:比如把一个构造函数A的方法赋值为另一个构造函数B,然后调用该方法,使构造函数A在构造函数B内部执行,这是构造函数B就拥有了构造函数A中定义的属性和方法。这就是B类继承A类。

    function extend(Sub,Sup){  var F = function(){};  //新建一个临时构造函数,避免直接new Sup时会消耗太多内存  F.prototype = Sup.prototype;  Sub.prototype = new F(); //实例化时,将原型传递给实例  Sub.prototype.constructor = Sub; //恢复子类的构造函数  Sub.sup = Sup.prototype;  //在子类中定义本地属性存储超类原型,避免子类与超类耦合  if(Sup.prototype.constructor === Object.prototype.constructor){    Sup.prototype.constructor = Sup;  }}function A(x,y){  this.x = x;  this.y = y;}A.prototype.add = function(){  return (this.x-0) + (this.y-0);  //转换为数值}function B(x,y){  A.apply(this,[x,y]);   //将参数传递}B.prototype.add = function(){  //单独为子类定义同名函数,避免代码耦合  return B.sup.add.call(this);}extend(B,A);var b = new B(1,2);console.log(b.add()); //3
  2. 原型继承

    原型继承是js中最通用的继承方式,不用实例化对象,通过直接定义对象,并被其他对象引用,这样形成的一种继承关系,其中引用对象被称为原型对象。

    function A(){  this.color = 'red';}function B(){}B.prototype=new A();var b=new B();console.log(b.color);
  3. 克隆继承

    通过对象克隆方式继承,可以避免赋值对象成员带来的低效。

    Function.prototype.clone = function(obj){  function Temp(){};  Temp.prototype=obj;  return new Temp();}function A(){  this.color = "red";}var o = Function.clone(new A());console.log(o.color);
  4. 混合继承

    混合继承是把多种继承方式一起使用,发挥各个优势,来实现各种复杂的应用。最常见的就是把类继承和原型继承一起使用。

    function A(x,y){  this.x=x;  this.y=y;}A.prototype.add = function(){  return (this.x-0)+(this.y-0);}function B(x,y){  A.apply(this,[x,y]);}B.prototype=new A();var b =new B(3,4);console.log(b.add());
  5. 多重继承

    JavaScript原型继承不支持多重继承,但可通过混合模式来实现多重继承。

    function A(z){  this.z=z;}A.prototype.hi=function(){  console.log('hi');}function B(y){  this.y=y;}B.prototype.hello=function(){  console.log('hello');}Function.prototype.extend = function(obj){  for(var item in obj){    this.constructor.prototype[item]=obj[item];  //复制继承,C是一个对象了  }}function C(z,y){  A.call(this,z);  B.call(this,y);}C.extend(new A(1));C.extend(new B(2));C.hi();C.hello();console.log(C.z);console.log(C.y);
原创粉丝点击