TypeScriptでクラスのコンストラクタを定義する
環境情報
Windows10 64bit
TypeScript Version 4.4.4
Windows10 64bit
TypeScript Version 4.4.4
Windows10 64bit TypeScript Version 4.4.4
構文
class クラス名{
constructor(変数名1: string,変数名2: number) {処理コード }
}
class クラス名{
constructor(変数名1: string,変数名2: number) {処理コード }
}
class クラス名{ constructor(変数名1: string,変数名2: number) {処理コード } }
使用例
//クラス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}`);
}
}
//クラスのインスタンスの生成
const cft = new User('become smart',30);
//クラスの関数を呼び出す
cft.funA();
//クラス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}`);
}
}
//クラスのインスタンスの生成
const cft = new User('become smart',30);
//クラスの関数を呼び出す
cft.funA();
//クラス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}`); } } //クラスのインスタンスの生成 const cft = new User('become smart',30); //クラスの関数を呼び出す cft.funA();
実行結果
>tsc
>ts-node arkgame.js
コンストラクタを実行します
名前:山田 太郎,年齢:30
>tsc
>ts-node arkgame.js
コンストラクタを実行します
名前:山田 太郎,年齢:30
>tsc >ts-node arkgame.js コンストラクタを実行します 名前:山田 太郎,年齢:30