LoginSignup
0
1

More than 5 years have passed since last update.

JS の class でメソッドを動的に呼ぶ小さいメモ

Posted at
class Hoge {
  constructor(){
    this.arr = [
      "hoge1",
      "hoge2",
      "hoge3"
    ]
  }
  hoge1() { console.log(1) }
  hoge2() { console.log("piyo") }
  hoge3() { console.log(100) }

  hoge(){
    var that = this
    this.arr.forEach(function(v, i, a){
      that[v]();
    })
  }
}

this を that に入れているけど..他に方法ありますでしょうか..。

> h = new Hoge()
# Hoge { arr: [ 'hoge1', 'hoge2', 'hoge3' ] }
> h.hoge()
# 1
# piyo
# 100
# undefined
0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1