我正在努力弄清各种javascript概念,而我无法理解的一件事是为什么它起作用:
var counterObject = {
counter: 0,
start: function () {
this.i++;
console.log(this.i);
}
};
setInterval(() => counterObject.start(), 1000);
但是,当我尝试使它成为递归函数时,我无法访问计数器变量:
var counterObject = {
counter: 0,
start: function () {
setInterval(function() {
this.i++;
console.log(this.i);
this.start;
}, 1000)
}
};
counterObject.start();
这将始终返回NaN,而我似乎无法理解为什么?只是学习,对我来说就轻松了;)
答案 0 :(得分:0)
您的代码中有几个问题。我将尝试在以下代码的注释中解释其中的大多数
var counterObject = {
counter : 0,
start : function() {
const that = this;
setInterval( function() {
// This function has a different scope so `this` is not your `counterObject`
// anymore. In order to use it you need to make a reference to it
/*
this.i++;
console.log( this.i );
this.start;
*/
// i? You probably meant counter, btw
that.counter++;
console.log( that.counter );
// Invoking a function always need parenthesis, so you should add those
// to make the recursive call
that.start();
}, 1000 );
}
};
counterObject.start();