##きっかけ
初めてconstructorの引数を見たときに、処理の内容がわからず混乱した。
##理解した方法
- 省略されているコードを分解して理解した。備忘録として残す。
class Dog {
//コンストラクター
constructor(private categry: string, private weight: number){}
// toStringメソッド
public toString {
return this.category + ':' + this.weight + 'kg'
}
}
let name = new Dog('豆柴', 8);
console.log(name.toString()); //結果:豆柴:8kg
//以下のコードと同じ
class Dog{
//privateプロパティ
private category: string;
private weight: number;
public constructor(category: string, weight: number) {
this.category = category;
this.weight = weight;
}
// toStringメソッド
public toString {
return this.category + ':' + this.weight + 'kg'
}
}
let name = new Dog('豆柴', 8);
console.log(name.toString()); //結果:豆柴:8kg