見出し画像

【ワンピースで覚えるTypeScript】第18回 this(JavaScript学習者向け)

今回はTypeScriptにおけるthisについて解説します。

呼び出し方によって変わることは分かっていると思いますが、さらにその理解を深めてもらえればと思います。


class Character {
  constructor(public name: string) {}
  introduce(): void {
    console.log(this);
    console.log(`私は${this.name}です`);
  }
}

const luffy = new Character("ルフィ");
luffy.introduce();//thisはluffy
const nami = new Character("ナミ");
nami.introduce();//thisはnami
//luffy_introduceに入っている関数オブジェクトを代入
const luffy_introduce = luffy.introduce;
//luffy_introduce(); //thisがundefined
//thisを使うものはメソッド記法を利用した方が良い

//アロー関数におけるthis
//=>自分自身のthisを持たない
class Character1 {
  name: string;
  bounty: number;
  constructor(name: string, bounty: number){
    this.name = name;
    this.bounty = bounty;
  }
  stronger(Chara: Character1[]): Character1[]{
    console.log(this);
    return Chara.filter(c => c.bounty > this.bounty);
  }                          //strongerのthisを受け継ぐ

  /*stronger2(Chara: Character1[]): Character1[] {
    return Chara.filter(function(c){ return c.bounty > this.bounty});
  }*/                             //thisが型?(どう呼ばれるか分からないから)

  stronger3(Chara: Character1[]): Character1[] {
    const _this = this;//thisを別の変数にしておく
    //stronger3メソッドの呼び出し時は thisはusopp
    //コールバック関数時には改めて関数よ呼び出されるので undefined
    return Chara.filter(function (c) { return c.bounty > _this.bounty });
  }
}

const usopp = new Character1("ウソップ", 500_000_000);
const jinbe = new Character1("ジンベエ", 1_100_000_000);
const chopper = new Character1("チョッパー", 1_000);
console.log(usopp.stronger([jinbe, chopper]));
console.log(usopp.stronger3([jinbe, chopper]));

//thisを操作するメソッド
//func.apply(thisArg, [argsArray])
//関数funcを、thisをthisArgにして呼び出す
class Character2 {
  name: string;
  bounty: number;
  constructor(name: string, bounty: number) {
    this.name = name;
    this.bounty = bounty;
  }
  stronger(Chara: Character2[]): Character2[] {
    return Chara.filter(c => c.bounty > this.bounty);
  }
}
const usopp2 = new Character2("ウソップ", 500_000_000);
const jinbe2 = new Character2("ジンベエ", 1_100_000_000);
const chopper2 = new Character2("チョッパー", 1_000);

console.log(chopper2.stronger([usopp2, jinbe2]));
//thisはchopper2
console.log(chopper2.stronger.apply(usopp2, [[usopp2, jinbe2]]));
//thisがusopp2になった

//func.call([thisArg[, arg1, arg2, ...argN])
//関数funcを、thisをthisArgにして呼び出す
console.log(chopper2.stronger([usopp2, jinbe2]));
console.log(chopper2.stronger.call(usopp2, [usopp2, jinbe2]));

//func.bind(thisArg)
//func関数を、thisをthisArgに固定する
const chopper_stronger = chopper2.stronger.bind(chopper2);
//thisをchopper2に固定
console.log(chopper_stronger([jinbe2, usopp2]));
console.log(chopper_stronger.call(jinbe2, [jinbe2, usopp2]));

この記事が気に入ったらサポートをしてみませんか?