JS继承有哪些方式

方式一:es6继承

<script>
    class Parent{
        constructor(){
            this.age = 18;
        }
    }
    class Child{
        constructor(){
            this.name = '张山';
        }
    }
    let o1 = new Child();
    console.log(o1.name,o1.age);//'张山' undefined
</script>
<script>
    class Parent{
        constructor(){
            this.age = 18;
        }
    }
    class Child extends Parent{
        constructor(){
            super();
            this.name = '张山';
        }
    }
    let o1 = new Child();
    console.log(o1.name,o1.age);//'张山' 18
</script>

方式二:原型链继承

        1、如果父类实例的属性是引用类型的时候,其实父类的实例属性会成为子类的原型属性,子类创建的所有实例都会共享这些方法,修改一个实例的这个属性,其他实例的属性也会被修改。

        2、子类型在实例化时不能给父类型的构造函数传参。

<script>
    function Parent(){
        this.age = 18;
    }
    function Child(){
        this.name = '张山';
    }
    let o1 = new Child();
    console.log(o1.name,o1.age);//'张山' undefined
</script>
<script>
    function Parent(){
        this.age = 18;
    }
    function Child(){
        this.name = '张山';
    }
    Child.prototype = new Parent();
    let o1 = new Child();
    console.log(o1.name,o1.age);//'张山' 18
</script>

方式三:借用构造函数

        1、只能在构造函数中调用方法 函数不能重用 就是每次子类生成实例的时候都会生成一次属性和方法。
        2、子类无法访问到父类原型上的方法。

<script>
    function Parent(){
        this.age = 18;
    }
    function Child(){
        this.name = '张山';
        Parent.call(this);
    }
    let o1 = new Child();
    console.log(o1.name,o1.age);//'张山' 18
</script>

方式四:组合继承

        调用了两次父类构造函数 比较耗内存。

<script>
    function Parent(){
        this.age = 18;
    }
    function Child(){
        //借用构造函数
        Parent.call(this)
        this.name = '张山';
    }
    //原型链继承
    Child.prototype = new Parent();
    let o1 = new Child();
    console.log(o1.name,o1.age);//'张山' 18
</script>

猜你喜欢

转载自blog.csdn.net/m0_73460278/article/details/126989579