gpt4 book ai didi

javascript - 修改 Meteor.setInterval 函数中的类属性

转载 作者:行者123 更新时间:2023-12-03 10:59:17 26 4
gpt4 key购买 nike

我需要做:

TestClass = function(){
this.left =10
this.finterval = function(){
console.log("this.finterval:"+JSON.stringify(intervalId))
this.left = this.left -1
Meteor.clearInterval(intervalId)
}
var intervalId = Meteor.setInterval(this.finterval,1000)
console.log("this.intervalId:" + this.intervalId)
}

有没有办法在interval方法中修改this.left?

最佳答案

this 始终引用当前作用域,因此如果您嵌套函数,则需要将其分配给另一个 var(例如 self):

TestClass = function(){
this.left =10
var self = this;
this.finterval = function(){
console.log("this.finterval:"+JSON.stringify(intervalId))
self.left = self.left -1
Meteor.clearInterval(intervalId)
}
var intervalId = Meteor.setInterval(this.finterval,1000)
console.log("this.intervalId:" + this.intervalId)
}

关于javascript - 修改 Meteor.setInterval 函数中的类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28161155/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com