关于继承

来源:互联网 发布:c语言continue在if中 编辑:程序博客网 时间:2024/05/22 01:35

继承的几种方式

  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);

这里写图片描述

原创粉丝点击