クラスを定義するサンプルです
サンプル
例)クラスを定義する
class CalcClass{
// メンバ変数
private x:number = 0;
private y:number = 0;
// コンストラクタ
constructor(x:number, y:number){
this.x = x;
this.y = y;
}
// 足し算メソッド
add():number{
return this.x + this.y;
}
// 掛け算メソッド
multiplication():number{
return this.x * this.y;
}
}
// クラスをnewしてメソッドを呼び出す
let c = new CalcClass(2, 3);
console.log(c.add());
console.log(c.multiplication());
結果
5 6
備考
- TypeScriptのクラスの宣言は、型の指定以外はJavaScriptと同様です。