「React」extendsでES6のクラスを継承する
書式
class 子クラス extends 親クラス{
constructor(変数1,変数2,変数3,xxx) {
/*親クラスのメンバー変数1と変数2を引用*/
super(変数1,変数2);
処理コード
}
}
使用例
<!DOCTYPE html>
<html>
<body>
<script>
/*親クラスCarの定義*/
class Car {
/*コンストラクタの定義*/
constructor(name,addr) {
this.brand = name;
this.addr = addr
}
/*メソッドの定義*/
func() {
return '車:' + this.brand +' ,場所:' + this.addr;
}
}
/*extendsでクラスの継承*/
class CarInfo extends Car {
/*コンストラクタの定義*/
constructor(name, addr,mod) {
/*superで親クラスの変数を継承*/
super(name,addr);
this.model = mod;
}
/*メソッド*/
show() {
return this.func() + ' ,生産国:' + this.model
}
}
/*クラスのインスタンスを生成*/
cftcar = new CarInfo("日産", "東京","日本");
document.write(cftcar.show());
</script>
</body>
</html>
実行結果
車:日産 ,場所:東京 ,生産国:日本