JS継承の方法は何ですか

 

方法 1: 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>

方法 2: プロトタイプ チェーンの継承

        1. 親クラス インスタンスの属性が参照型の場合、親クラスのインスタンス属性は、実際にはサブクラスのプロトタイプ属性になります. サブクラスによって作成されたすべてのインスタンスは、これらのメソッドを共有します. 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>

方法 3: コンストラクターを借用する

        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>

方法 4: 複合継承

        親クラスのコンストラクターを 2 回呼び出すと、より多くのメモリが消費されます。

<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