Cover Image for [JavaScript] ClassMethod を代入すると意図しない動きをする

[JavaScript] ClassMethod を代入すると意図しない動きをする

概要

  • ClassFunction を変数に代入すると、参照が代入されるだけかと思ったが意図しない動きをする
  • 代入する際に this が暗黙的に変更されるのが原因
  • function を代入する際に代入する際にbindでthisを明示的に束縛してあげれば解決する

意図しない動きをするパターン

class SomeClass {
  param: string;
  
  constructor() {
    this.param = "test";
  }
  
  say() {
    console.log(this)
    console.log(`${this.param}`);
  }
}

  

const test = new SomeClass()
test.say()
  

const testMethod = test.say
testMethod()

playground

このまま実行すると、最終行で console.log(this) が呼ばれた際に this が undefined になりその次の行でエラーが出る

解決策

class SomeClass {
  param: string;
  
  constructor() {
    this.param = "test";
  }
  
  say() {
    console.log(this)
    console.log(`${this.param}`);
  }
}

  

const test = new SomeClass()
test.say()
  

const testMethod = test.say.bind(test)
testMethod()

playground

bind で this を明示的に束縛すると意図した通りの動きをする