What are the ways of JS inheritance

 

Method 1: es6 inheritance

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

Method 2: Prototype Chain Inheritance

        1. If the attribute of the parent class instance is a reference type, the instance attribute of the parent class will actually become the prototype attribute of the subclass. All instances created by the subclass will share these methods. Modify this attribute of one instance and the attributes of other instances will also be modified.

        2. The subtype cannot pass parameters to the constructor of the parent type when it is instantiated.

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

Method 3: Borrow the constructor

        1. The method function can only be called in the constructor and cannot be reused, that is, the properties and methods will be generated every time a subclass generates an instance.
        2. Subclasses cannot access the methods on the prototype of the parent class.

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

Method 4: Combined Inheritance

        Calling the parent class constructor twice consumes more memory.

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

Guess you like

Origin blog.csdn.net/m0_73460278/article/details/126989579