In the given scenario, there is an error in calling the function and then attempting to use .bind
on the result. The correct way to write this code is as follows (where the false
argument is passed within the bind
method):
class Sample {
CheckIfDeviceIsAvailable(forceCheck: boolean) {
alert(forceCheck);
}
execute() {
setInterval(this.CheckIfDeviceIsAvailable.bind(this, false), 2000);
}
}
const sample = new Sample();
sample.execute();
To maintain the lexical scope more concisely, you can utilize an arrow function:
class Sample {
CheckIfDeviceIsAvailable(forceCheck: boolean) {
alert(forceCheck);
}
execute() {
setInterval(() => this.CheckIfDeviceIsAvailable(false), 2000);
}
}
const sample = new Sample();
sample.execute();
Alternatively, you can achieve the same result by introducing an intermediate variable like so:
class Sample {
CheckIfDeviceIsAvailable(forceCheck: boolean) {
alert(forceCheck);
}
execute() {
const _this = this;
setInterval(function () { _this.CheckIfDeviceIsAvailable(false) }, 2000);
}
}
const sample = new Sample();
sample.execute();