classクラスの継承

6156 ワード

##classクラスの継承1.Classはextendsキーワードで継承できます
class Point {
    
}

class ColorPoint extends Point {
}

上記のコードは、extendsキーワードを介してPointクラスのすべての属性とメソッドを継承するColorPointクラスを定義します.
superキーワードは、親の構造関数を表し、親のthisオブジェクトを新規作成します.
class fruit {
    constructor(price, weight) {
        this.price = price;
        this.weight = weight
    }
    total(cont) {
        return cont * this.price * this.weight;
    }
}
class apple extends fruit {
    constructor(price, weight) {
        super(price, weight) // 
    }
    total(cont) {
        return super.total(cont)// tatal 
    }
}

サブクラスはconstructorメソッドでsuperメソッドを呼び出す必要があります。そうしないと、インスタンスを新規作成するときにエラーが発生します。

class Point { /* ... */ }

class ColorPoint extends Point {
  constructor() {
  }
}

let cp = new ColorPoint(); // ReferenceError
 : 


class fruit {
    constructor(price, weight) {
        this.price = price;
        this.weight = weight;

    }
    total() {
        return this.price * this.weight;
    }
}
class Apple extends fruit {
    constructor(price, weight) {
        super(price, weight) //
    }
}
class Banner extends fruit {
    constructor(price, weight) {
        super(price, weight)
    }
}
class Bear extends fruit {
    constructor(price, weight) {
        super(price, weight)
    }
}
const app = new Apple(10, 10);
const banner = new Banner(10, 10);
const bear = new Bear(10, 10);
console.log(app.total() + banner.total() + bear.total());

まとめ:1.Classはextendsキーワードで継承できます
2.親の構造関数を表し、親のthisオブジェクトを新規作成します.
3.サブクラスはconstructorメソッドでsuperメソッドを呼び出す必要があります.そうしないと、インスタンスを新規作成するときにエラーが発生します.これは、サブクラス独自のthisオブジェクトが、親のコンストラクション関数によって作成され、親と同じインスタンス属性とメソッドが得られ、その後、それを加工し、サブクラス独自のインスタンス属性とメソッドを加えなければならないからです.superメソッドを呼び出さないと、サブクラスはthisオブジェクトを取得できません.
4.ColorPointは親のPointを継承しますが、そのコンストラクション関数はsuperメソッドを呼び出さず、新しいインスタンス・タイムズが間違っています.