【问题标题】:setInterval in ES6 object [duplicate]ES6对象中的setInterval [重复]
【发布时间】:2018-09-07 14:34:56
【问题描述】:

我有以下对象。我一直工作到使用 setinterval 为止。 我意识到this 变成了对象timeout

class test{
    constructor(){
        this.counter = 0
    }
    startCounter(){
        this.increment()
       setInterval(this.increment, 1000)
    }
    increment(){
        this.counter++
        console.log(this.counter)
    }

}

var t = new test()
t.startCounter()

输出:

1
NaN
NaN
NaN
NaN
NaN
NaN

How to access the correct `this` inside a callback? 建议我应该使用var self = this 但是 ES6 不支持私有变量

【问题讨论】:

  • @T.J Crowder 此链接没有 ES6 对象。我没有看到这是重复的
  • 该问题与“ES6 对象”无关。它与this 有关。如果你花时间阅读答案,你就会明白。
  • 也许解决方案是相同的,但场景不同@T.J.克劳德
  • @JoseMato - 再次,没关系。
  • @TSR - 那里的答案远不止于此。花时间真正阅读答案并消化他们所说的内容,而不是专注于那里没有涵盖这些内容并在 30 秒后放弃的想法。这在那里的答案中得到了很好的解决,例如this one

标签: javascript node.js object methods setinterval


【解决方案1】:

请试试这个:

class test{
    constructor(){
        this.counter = 0
    }
    startCounter(){
        this.increment()
       setInterval(this.increment.bind(this), 1000)
    }
    increment(){
        this.counter++
        console.log(this.counter)
    }

}

var t = new test()
t.startCounter()

【讨论】:

  • 我们不需要另一个回答这个问题。
  • 我看不出这个答案有什么问题。
  • 也许你应该添加()=>this.increment()作为提到es6的标题。
  • @appleapple - 所有这些都被链接的 dupetarget 覆盖。这就是为什么这个问题的另一个答案没有用的部分原因。
  • @T.J.Crowder 这个答案太复杂了,无法成为这个问题的答案,恕我直言。这个答案没有错(好吧,它缺少一些解释和 es6 的东西,所以我没有投票)。
猜你喜欢
  • 2018-11-14
  • 1970-01-01
  • 2017-05-02
  • 1970-01-01
  • 2018-12-01
  • 2021-12-21
  • 2020-04-19
  • 2018-04-12
  • 1970-01-01
相关资源
最近更新 更多