iRSSの日記

はてなダイアリーiRSSの日記の続き

thisの動きに惑う

typescript
type Handler = (name: string) => void;

class A {
  public hello(name: string) {
    console.log("hello " + name, "this:`", this, "`");
  }
}

class B {
  public world(name: string) {
    console.log("world " + name, "this:`", this, "`");
  }
}

const a = new A();
a.hello("tokyo");

const b = new B();
b.world("aichi");

class Runner {
  public handlers: { [path: string]: Handler } = {
    "/hello": a.hello,
    "/world": b.world,
  };

  public run(path: string, name: string) {
    this.handlers[path](name);
  }
}

new Runner().run("/hello", "hokkaido");

helloで、呼び出された、a.helloのthisがaになると思うのだけど、そんなことはないのが、jsのthis.

f:id:iRSS:20200724204209p:plain


## 解決できた

class Runner {
  public handlers: { [path: string]: Handler } = {
    "/hello": a.hello.bind(a),  // <-ここでbindすれば、よいのだ(いやだけど)
    "/world": b.world.bind(b),
  };

  public run(path: string, name: string) {
    this.handlers[path](name);
  }
}

Reactでも出てきたやつだ。繋がった。
ja.reactjs.org

f:id:iRSS:20200724205907p:plain