0

Let me start with an example :

class Test {
  constructor() {
    this.isOn = false;
  }

  general(method) {
    method();
  }

  off() {
    this.isOn = false;
  }

  atTime() {
    // this.off(); --> works
    this.general(this.off); // --> does not work
  }
}

let test = new Test();
test.atTime();

I thought I would pass this.off as an argument but it seems I cannot.

Here's a live example : https://goo.gl/9hRTTw

maxime1992
  • 22,502
  • 10
  • 80
  • 121
  • 1
    This didn't change with ES6, it's the same issue as always. – Bergi Mar 17 '16 at 13:24
  • You're right, it's very similar. But still, I do not understand. I tried to use self, I tried to bind(this) but it does not work. If you could modify the demo and send me back the link I would really appreciate @Bergi ! – maxime1992 Mar 17 '16 at 13:29
  • `this.general(this.off.bind(this))` *does* work. Please show us what exactly you have done. – Bergi Mar 17 '16 at 13:29
  • Ooooh ok I see ! I tried `this.general(this.off).bind(this);` thanks a lot ! (rewrite it as an answer if you want and I'll validate it) – maxime1992 Mar 17 '16 at 13:31
  • 1
    Or do it like this? `this.general(() => {this.off()});` – yeouuu Mar 17 '16 at 13:32
  • I like this syntax, thanks @yeouuu :) `this.general(_ => this.off);` – maxime1992 Mar 17 '16 at 13:38
  • 2
    @Maxime: I won't write an answer, the duplicate already explains everything (including the arrow function solution). Notice that you still need to invoke `off`, i.e. `this.general(_ => this.off())` – Bergi Mar 17 '16 at 13:40

0 Answers0