### クラス
class Person { name:string = 'no-name' mail?:string age?:number print():void { const ml:string = this.mail ? this.mail : 'no-mail' const ag:number = this.age ? this.age : -1 console.log(this.name + '(' + ml + ',' + ag + ')') } } const taro = new Person() taro.name = 'taro' taro.mail = 'taro@gmail.com' taro.age = 39 taro.print()
### コンストラクタ
class Person { name:string = 'no-name' mail?:string age?:number constructor(name:string, mail:string = 'no-mail', age:number = -1){ this.name = name this.mail = mail this.age = age } print():void { console.log(this.name + '(' + this.mail + ',' + this.age + ')') } } const taro = new Person('taro', 'taro@gmail.com', 39) const hanako = new Person('hanako', 'hanako@gmail.com') const sachiko = new Person('sachiko') taro.print() hanako.print() sachiko.print()
### インスタンスのクラスを調べる
console.log(taro instanceof Person === hanako instanceof Person === true) console.log(taro.constructor.name) console.log(hanako.constructor.name) console.log(Person.name)
### クラスの継承
extendsで継承する
enum School { junior='junior', juniorHigh = 'juniorHigh', high = 'high', other = 'other' } class Student extends Person { school?:School grade?:number constructor(name:string, school:School, grade:number){ super(name) this.school = school this.grade = grade switch(school){ case School.junior: this.age = 6 + this.grade; break case School.juniorHigh: this.age = 12 + this.grade; break case School.high: this.age = 15 + this.grade; break default: this.age = -1 } } } const taro = new Person('taro', 'taro@gmail.com', 39) const hanako = new Student('hanako', School.high, 2) taro.print() hanako.print()
### メソッドのオーバーライド
– 継承しているクラスの中にメソッドを追加する
print():void { let gd:string = this.grade ? String(this.grade) : '-' switch(this.grade){ case 1:gd += 'st'; break case 2:gd += 'nd'; break case 3:gd += 'rd'; break default: gd += 'th' } console.log(this.name + '(' + this.school + ' school: ' + gd + ' grade)') }
### アクセス修飾子
public: 外部から自由にアクセス
protected: クラスおよびクラスを継承したサブクラス
private: クラス内のみ
protected name:string = 'no-name' private mail:string public age:number
### setterとgetter
class Student extends Person { school?:School private grade_num:number = -1 get gradeN():number { return this.grade_num } set gradeN(n:number){ this.grade_num = n this.grade = String(n) } private gr_str:string = '' get grade(): string { return this.gr_str } private set grade(pr:string){ let gd = pr switch(this.gradeN){ case 1: gd += 'st'; break case 2: gd += 'nd'; break case 3: gd += 'rd'; break default: gd += 'th' } this.gr_str = gd } constructor(name:string, school:School, grade:number){ super(name) this.school = school this.gradeN = grade } print():void { let gd:string = this.grade ? String(this.grade) : '-' console.log(this.name + '(' + this.school + ' school: ' + gd + ' grade)') } }
ふむ