代码之家  ›  专栏  ›  技术社区  ›  user3024827

基本的javascript概念理解[duplicate]

  •  0
  • user3024827  · 技术社区  · 6 年前

    我试图了解各种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();
    

    这总会让楠回来,我好像不明白为什么?只是学习,所以对我的人放轻松;)

    1 回复  |  直到 6 年前
        1
  •  0
  •   Ivan Drinchev    6 年前

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

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