0

I'm doing some experiments with class and weirdly in this special case, setInterval is only called once if I pass test.method1() and I get error if I pass test.method1, why ?

class Test {

  constructor() {
    this.counter = 0;
    (async () => {
      this.test();
    }
    )();
  }

  test() {
    this.method1();
  }
  method1() {
    let value;
    value = this.method2();
    console.log(this.counter);

  }
  method2() {
    this.counter++;
    return this.counter;
  }
}

let test = new Test();
let id = setInterval(test.method1(), 1000);
Emanresu a
  • 248
  • 2
  • 11
user310291
  • 36,946
  • 82
  • 271
  • 487
  • 3
    https://stackoverflow.com/questions/15886272/what-is-the-difference-between-a-function-call-and-function-reference and https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work?r=SearchResults&s=6|229.0337 – Teemu May 09 '22 at 16:28
  • 1
    It's getting called once because you are calling it - You need to do this: `let id = setInterval(() => test.method1(), 1000)` – inorganik May 09 '22 at 17:03

2 Answers2

1

I get error if I pass test.method1, why ?

Because this context is lost. If you console.log(this) inside method1, you will not get an instance of Test. Basically, it's

const orphanedMethod = test.method1; // I'm not bound to the test variable now...
setInterval(orphanedMethod, 1000); // and if I try to access `this`, I'll get Window or sth like that

Either make method1 an arrow function:

method1 = () => {
    let value;
    value = this.method2();
    console.log(this.counter);
}

or explicitly bind it to the object when calling:

setInterval(test.method1.bind(test), 1000);
mbojko
  • 13,503
  • 1
  • 16
  • 26
  • 1
    Changing `method1` into an arrow function should come with a disclaimer. Using an arrow function is a shortcut for `this.method1 = () => { ... }` placed inside the constructor. Meaning that it is not present on `Test.prototype`. It will also be an iterable property. – 3limin4t0r May 09 '22 at 17:02
1

your error is JS cannot find method1 method inside test method because method1 is only called inside your test method. To do test.method1(), you should put your method1 definition inside your test method.

another thing is setInterval simply did not work, probably because you stored it in a variable and did not call id(). It only worked once because you explicitly called test.method1() inside your setInterval

DEN DEN G
  • 31
  • 2