TypeScriptでクラス継承のサンプル
書式
class クラスB extends クラスA{処理コード}
const cft = new クラスB(メンバー1,メンバー2);
使用例
//クラスUserの定義
class User {
//メンバーの宣言
private username: string;
private age: number;
// コンストラクタの定義
constructor(username: string,age: number) {
this.username = username;
this.age = age;
console.log('親クラスのコンストラクタを実行します');
}
//関数funAの定義 thisキーワードで
funA() {
console.log(`名前:${this.username},年齢:${this.age}`);
}
}
// extendsでUserクラスを継承
class UserInfo extends User {
funB() {
console.log('funB: tesr message2');
}
}
//継承クラスのインスタンスの生成
const cft = new UserInfo('山田 太郎',30);
//親クラスの関数を呼び出す
cft.funA();
//自身クラスの関数を呼び出す
cft.funB();
//クラスUserの定義
class User {
//メンバーの宣言
private username: string;
private age: number;
// コンストラクタの定義
constructor(username: string,age: number) {
this.username = username;
this.age = age;
console.log('親クラスのコンストラクタを実行します');
}
//関数funAの定義 thisキーワードで
funA() {
console.log(`名前:${this.username},年齢:${this.age}`);
}
}
// extendsでUserクラスを継承
class UserInfo extends User {
funB() {
console.log('funB: tesr message2');
}
}
//継承クラスのインスタンスの生成
const cft = new UserInfo('山田 太郎',30);
//親クラスの関数を呼び出す
cft.funA();
//自身クラスの関数を呼び出す
cft.funB();
//クラスUserの定義 class User { //メンバーの宣言 private username: string; private age: number; // コンストラクタの定義 constructor(username: string,age: number) { this.username = username; this.age = age; console.log('親クラスのコンストラクタを実行します'); } //関数funAの定義 thisキーワードで funA() { console.log(`名前:${this.username},年齢:${this.age}`); } } // extendsでUserクラスを継承 class UserInfo extends User { funB() { console.log('funB: tesr message2'); } } //継承クラスのインスタンスの生成 const cft = new UserInfo('山田 太郎',30); //親クラスの関数を呼び出す cft.funA(); //自身クラスの関数を呼び出す cft.funB();
実行結果
親クラスのコンストラクタを実行します
名前:山田 太郎,年齢:30
funB: tesr message2
親クラスのコンストラクタを実行します
名前:山田 太郎,年齢:30
funB: tesr message2
親クラスのコンストラクタを実行します 名前:山田 太郎,年齢:30 funB: tesr message2