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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基本的javascript概念理解[重复]相关的知识,希望对你有一定的参考价值。

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

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

答案

您的代码中有几个问题。我将尝试在以下代码的注释中解释其中的大部分内容

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();

以上是关于基本的javascript概念理解[重复]的主要内容,如果未能解决你的问题,请参考以下文章

JavaScript 代码片段

精心收集的 48 个 JavaScript 代码片段,仅需 30 秒就可理解

html PHP代码片段: - AJAX基本示例:此代码演示了使用PHP和JavaScript实现的基本AJAX功能。

Python类OOPs概念[重复]

48个值得掌握的JavaScript代码片段(上)

译理解JavaScript闭包——新手指南