Es 6 class継承およびsuper特性の詳細


一、クラスの継承


classはextendsキーワードで継承されます
class a{
     
	constructor(x, y) {
     
	    this.x = x;
		this.y = y;
	}
	toString(){
     
		return this.x+' '+this.y;
	}
}
//  a, z 
class b extends a{
     
	constructor(x, y, z) {
     
		super(x, y);// this 
		this.z = z;
	}
	toString2(){
     
		return super.toString()+' '+this.z
	}
}

usper上記の例では、親クラスのインスタンスオブジェクトthisが作成されています.

二、super詳細


superキーワードは、関数(super())として使用してもよいし、オブジェクト(super)として使用してもよい
  • superは親のコンストラクション関数を表し、サブクラスのコンストラクション関数はsuper
  • を1回実行する必要がある.
    constructor(x, y, z) {
         
    	super(x, y);// this 
    	this.z = z;
    }
    

    superは親aの構造関数を表すが、サブクラスbの例を返し、super内部のthisが指すbであるsuper()a.prototype.constructor.call(this)に相当する
  • superを関数とする場合はサブクラスのコンストラクション関数のみで、カスタム関数では
  • とエラーが報告される.
    class a{
         }
    class b extends a{
         
    	m(){
         
    		super();// 
    	}
    }
    
  • superをオブジェクトとし、静的メソッドでは親を指し、通常のメソッドでは親のプロトタイプを指す.

  • 次に、一般的な方法を示します.
    class a{
         
    	aa(){
          return 233 }
    }
    class b extends a{
         
    	constructor(){
         
    		super();
    		console.log(super.aa()); 
    	}
    }
    
    var c = new b; //  233
    

    上記のコードでは、サブクラスbのsuper.aa()は、superを1つのオブジェクトとして使用する.このときsuperは通常の方法ではa.prototypeを指すので、super.aa()a.prototype.aa()に相当する(クラスのすべての方法はクラスのprototypeに定義され、constructorは除く).
    注意:superは親のプロトタイプオブジェクトを指すため、親インスタンスに定義されたメソッドまたはプロパティはsuperで呼び出すことはできませんが、プロトタイプに定義されたプロパティおよびメソッドは取得できます(a.prototype.x=233).
  • super親クラスのメソッドを呼び出すと、superは子クラスのthis
  • をバインドします.
     class a{
         
     	constructor(){
         
    		this.x = 1 
    	}
    	cout(){
          
    		console.log(this.x);
    	 }
    }
    class b extends a{
         
    	constructor(){
         
    		super();
    		this.x = 2 
    	}
    	bd(){
         
    		super.cout();
    	}
    }
    
    var c = new b;  
    b.bd() // 2
    

    以上の結果の出力値は2である、super.cout()はa.prototypeを呼び出します.しかし、aのprototype.cout()バインドbのthisが実際に実行されたのはsuper.cout.call(this)です