基本的javascript概念理解[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我试图了解各种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,我似乎无法理解为什么?只是学习如此轻松我的家伙;)

javascript function
1个回答
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();
© www.soinside.com 2019 - 2024. All rights reserved.