this引数 (this parameter)
アロー関数以外の関数とクラスのメソッドの第1引数はthisという特殊な引数を受けることができます。これは使用するコンテキストによってthisの意味するところが変わってしまうため、これらがどのコンテキストで使用されるべきなのかをTypeScriptに伝えるために使います。このthisは呼び出す側は意識する必要はありません。第2引数以降を指定してください。
tsclassMale {privatename : string;public constructor(name : string) {this.name =name ;}publictoString (): string {return `Monsieur ${this.name }`;}}classFemale {privatename : string;public constructor(name : string) {this.name =name ;}publictoString (this :Female ): string {return `Madame ${this.name }`;}}
tsclassMale {privatename : string;public constructor(name : string) {this.name =name ;}publictoString (): string {return `Monsieur ${this.name }`;}}classFemale {privatename : string;public constructor(name : string) {this.name =name ;}publictoString (this :Female ): string {return `Madame ${this.name }`;}}
上記クラスMale、Femaleはほぼ同じ構造ですがtoString()のメソッドの引数が異なります。
Male、Femaleはともに普通の用途で使うことができます。
tsconstmale :Male = newMale ("Frédéric");constfemale :Female = newFemale ("Frédérique");male .toString ();female .toString ();
tsconstmale :Male = newMale ("Frédéric");constfemale :Female = newFemale ("Frédérique");male .toString ();female .toString ();
ですが各インスタンスのtoString()を変数に代入すると意味が変わります。
tsconstmaleToStr : () => string =male .toString ;constfemaleToStr : (this :Female ) => string =female .toString ;maleToStr ();The 'this' context of type 'void' is not assignable to method's 'this' of type 'Female'.2684The 'this' context of type 'void' is not assignable to method's 'this' of type 'Female'.femaleToStr ();
tsconstmaleToStr : () => string =male .toString ;constfemaleToStr : (this :Female ) => string =female .toString ;maleToStr ();The 'this' context of type 'void' is not assignable to method's 'this' of type 'Female'.2684The 'this' context of type 'void' is not assignable to method's 'this' of type 'Female'.(); femaleToStr
femaleToStr()のコンテキストがFemaleではないとの指摘を受けています。このコードを実行することはできません。ちなみにこの対応をしていないmaleToStr()は実行こそできますが実行時に例外が発生します。
jsclassMale {// ...toString () {return `Monsieur ${this.name }`;}}
jsclassMale {// ...toString () {return `Monsieur ${this.name }`;}}
引数のthisを指定することによって意図しないメソッドの持ち出しを避けることができます。