美文网首页js
组合继承,寄生组合继承,class继承

组合继承,寄生组合继承,class继承

作者: 马甲要掉了 | 来源:发表于2020-05-20 16:57 被阅读0次

组合继承

function Parent(name){
    this.name = name
}
Parent.prototype.fn=function(){
    console.log(this.name);
}
function Child(name,age){
    Parent.call(this,name);
    this.age = age;
}
Child.prototype = new Parent();
let child = new Child('zhangsan','12');
child.fn() //zhangsan

说明:核心是在子类的构造函数中通过 Parent.call(this) 继承父类的属性,然后改变子类的原型为 new Parent() 来继承父类的函数。

这种继承方式优点在于构造函数可以传参,不会与父类引用属性共享,可以复用父类的函数,但是也存在一个缺点就是在继承父类函数的时候调用了父类构造函数,导致子类的原型上多了不需要的父类属性,存在内存上的浪费。

寄生组合继承

function Parent(name){
    this.name = name
}
Parent.prototype.fn=function(){
    console.log(this.name);
}
function Child(name,age){
    Parent.call(this,name);
    this.age = age;
}
function object(o){
    function F(){};
    F.prototype = o;
    return new F();
}
function prototype(child,parent){
    let prototype = object(parent.prototype);
    prototype.constructor = child;
    child.prototype = prototype;
}
prototype(Child,Parent);
let child = new Child('zhangsan','12')
child.fn();  //zhangsan

说明:核心是将父类的原型赋值给了子类,并且将构造函数设置为子类,这样既解决了无用的父类属性问题,还能正确的找到子类的构造函数。

class继承

class Parent{
    constructor(name){
        this.name = name;
    }
    getName(){
        console.log(this.name);
    }
}
class Child extends Parent{
    constructor(val){
        super(val);
    }
}
let child = new Child('zhangsan');
child.getName();  //zhangsan
child instanceof Parent // true

说明:核心在于使用 extends 表明继承自哪个父类,并且在子类构造函数中必须调用 super。
class 的本质还是函数,这种表达不过是一种语法糖。

相关文章

  • 组合继承,寄生组合继承,class继承

    组合继承 说明:核心是在子类的构造函数中通过 Parent.call(this) 继承父类的属性,然后改变子类的原...

  • ES5和ES6 实现继承方式

    在ES5 中:通过原型链实现继承的,常见的继承方式是组合继承和寄生组合继承;在ES6中:通过Class来继承 组合...

  • 二、js继承的几种方式及优缺点

    1、继承:原型链、借用构造函数、组合继承、原型式继承、寄生式继承、寄生组合继承

  • js继承方式

    类式继承 构造函数继承 组合继承 类式继承 + 构造函数继承 原型式继承 寄生式继承 寄生组合式继承 寄生式继承 ...

  • 继承

    原型继承 借用构造函数 组合继承 原型式继承 寄生式继承 寄生组合继承 优点: 因为组合继承最大的问题是无论什么...

  • js继承代码学习

    寄生组合式继承是除了class继承外,最好的继承方法,当然也很麻烦。

  • javaScript 实现继承方式

    JavaScript实现继承共6种方式:原型链继承、借用构造函数继承、组合继承、原型式继承、寄生式继承、寄生组合式继承。

  • 前端面试题总结【38】:javascript继承的 6 种方法

    原型链继承 借用构造函数继承 组合继承(原型+借用构造) 原型式继承 寄生式继承 寄生组合式继承 推荐: 持续更新...

  • js的继承

    面向对象的继承方式有很多种,原型链继承、借用构造函数继承、组合继承、原型式继承、寄生式继承、寄生式组合继承、深拷贝...

  • JS类的继承

    1.类式继承 构造函数继承 3.组合继承 4.原型继承 5.寄生式继承 6.寄生组合式继承

网友评论

    本文标题:组合继承,寄生组合继承,class继承

    本文链接:https://www.haomeiwen.com/subject/bienohtx.html