关于继承

继承的几种方式

  1. 原型链
/*原型链*/
    function SuperType() {
        this.property=true;
    }
    SuperType.prototype.getSuperValue=function () {
        return this.property;
    };
    function SubType(){
        this.subproperty=true;
    }
    SubType.prototype=new SuperType();
    SubType.prototype.getSubValue=function () {
        return this.subproperty;
    };
    var instance=new SubType();
    console.log(instance);

通过控制台可以看出原型链的方式
这里写图片描述
2. 借用构造函数继承

/*借用构造函数继承*/
function SuperType() {
    this.color=["blue","red"];
}
function SubType() {
    SuperType.call(this);//继承了color属性
}
var instance1=new SubType();
instance1.color.push("black");
console.log(instance1);

这里写图片描述

3.组合方式继承

/*组合方式继承*/
function SuperType(name){
    this.name=name;
    this.colors=["blue","white"];
}
SuperType.prototype.sayName=function () {
    console.log(this.name);
};

function SubType(age,name){
    SuperType.call(this,name);//通过构造函数方式继承
    this.age=age;
}
SubType.prototype=new SuperType();//通过原型的方式继承
Subtype.prototype.constructor=SubType;
Subtype.prototype.sayAge=function () {
    console.log(this.age);
};

var instance1=new SubType("hello",29);
console.log(instance1);

这里写图片描述

4.原型式继承
object.create()的profill方式

    function Object(o) {
    function F() {}
    F.prototype=o;
    return new F();
}

5.寄生组合式继承

 /*寄生组合式继承*/
  function inHeritPrototype(SuperType,SubType) {
      var prototype=Object(SuperType.prototype);//创建对象
      prototype.constructor=SubType;//增强对象
      SubType.prototype=prototype;
  }
  function SuperType(name){
      this.name=name;
      this.colors=["blue","white"];
  }
  SuperType.prototype.sayName=function () {
      console.log(this.name);
  };

  function SubType(age,name) {
      SuperType.call(this, name);
      this.age=age;
  }
  inHeritPrototype(SuperType,SubType);
  SubType.prototype.sayAge=function () {
      return this.age;
  };
  var instance1=new SubType("hello",28);
  console.log(instance1);

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值