В первом примере вы передаете ссылку на функцию без ее запуска.Когда он запускается, он запускается в глобальном контексте, где this
не определено, или this
относится к объекту Window
.Вы можете убедиться, что он действительно ссылается на объект Window
, зарегистрировав значение this.constructor.name
:
class MyClassName {
counter = 0;
// You are passing in a function name but not running it yet.
// It will be run in a global context by setInterval.
startInterval(){
setInterval(this.myFunc, 1000)
}
myFunc(){
// When run in global context, this no longer refers to our instance.
console.log(this.constructor.name);
this.counter++;
console.log(this.counter)
}
}
const mc = new MyClassName();
mc.startInterval();
Во втором примере функции стрелок используют this
того, где они объявлены, а не того места, где они выполняются.Таким образом, this
класса представлен ниже, даже если функция стрелки будет выполняться в глобальном контексте.
class MyClassName {
counter = 0;
// Arrow functions use the `this` of where they are declared, not where they are run.
// So the `this` of the class is captured below, even though the arrow function
// will run in the global context.
startInterval(){
setInterval(() => this.myFunc(), 1000);
}
myFunc(){
console.log(this.constructor.name);
this.counter++;
console.log(this.counter)
}
}
const mc = new MyClassName();
mc.startInterval();
Вы можете найти довольно хорошее резюме того, как именно это работает конкретно с setInterval
в документах MDN для функций стрелок .