常见继承方式

原型链+借用构造函数的组合继承

function parent(val){
    this.val=val;
}
parent.prototype.getvalue=function(){
    console.log(this.val);
}
function Child(val){
    parent.call(this,val);
}
Child.prototype=new parent();
var child=new Child(1);
child.getvalue();
console.log(child instanceof parent);

在子类的构造函数中通过parent.call(this)继承父类的属性,然后改变子类的原型为new parent()来继承父类函数。
这种继承的方式,优点在于构造函数可以传参,不会与父类引用属性共享,可以复用父类的函数,缺点是继承父类函数的时候调用父构造函数,导致子类的原型上多了不需要的父类属性,存在内存浪费。

寄生组合继承(优化上一种组合继承)

function parent(val){
    this.val=val;
}
parent.prototype.getvalue=function(){
    console.log(this.val);
}
function Child(val){
    parent.call(this,val);
}
//Object.create()方法创建一个新对象,使用现有的对象来提供新创建的对象的__proto__。 
Child.prototype=Object.create(parent.prototype,{
    constructor:{
        value:Child,
        enumerable:false,
        writable:true,
        configurable:true
    }
});
var child=new Child(1);
child.getvalue();
console.log(child instanceof parent);

将父类的原型赋值给子类,即解决了无用的父类属性问题,正确找到子类的构造函数。

ES6中class继承

class可以通过extends关键字实现继承,还可以通过static关键字定义类的静态方法。class关键字只是原型的语法糖,js继承依旧是基于原型实现的。

class parent{
    constructor(val){
        this.val=val;
    }
    getvalue(){
        console.log(this.val);
    }
}
class Child extends parent{
    constructor(val){
        super(parent);
        this.val=val;
    }
}
var child=new Child(1);
child.getvalue();
console.log(child instanceof parent);
function inheritPrototype(subType, superType){
    var prototype = Object.create(superType.prototype);       //创建对象
    prototype.constructor = subType;                   //增强对象
    subType.prototype = prototype;                     //指定对象
}

class实现继承核心在于使用extends表明继承自哪个父类,并且在子类构造函数中必须调用super,因为类似parent.call(this,val)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • property shorthand & short methods 示例: object destructuri...
    zshanjun阅读 201评论 0 0
  • 跳出舒适区是一个渐进的过程,就好比说,从我9月16号提出辞职以来,到现在还得在公司做收尾工作。 而这段时间内,我知...
    乔女侠阅读 111评论 0 0
  • 万有阴阳。生我者也分阴阳,异性相生为正印,同性相生为枭印。 正印生身有情,是正向引导自己,以舒适、平和等让人如浴春...
    坚冰至_Monsol阅读 1,530评论 0 55
  • 凤楼春 尘海偶相逢,若酒情浓。 影玲珑,婀娜瘦柳舞东风。 唇点绛,脸桃红。 杏眼流波明皓齿,髻浪卷云丛。 语难通,...
    刀剑啸九天阅读 828评论 1 2
  • 我们常常会告别,与友人、与家人、与同事、与恋人……告别以后的再见,有的稀松平常,有的弥足珍贵,有的再无可能…… 稀...
    想念你的名字阅读 216评论 2 4