【问题标题】:Calling setInterval and clearInterval functions inside multiple javascript objects在多个 javascript 对象中调用 setInterval 和 clearInterval 函数
【发布时间】:2014-11-01 12:14:13
【问题描述】:

我正在尝试在使用“new”运算符创建的 js 对象中使用“setInterval”和“clearInterval”函数。

html:

<button onclick="testList.push(new Test());">run</button>

js:

Test = function(){
   this.y = 0;
   this.dy = 10;
   that = this;
   this.interval = setInterval(function(){
        that.y += that.dy;
        if (that.y>300){
            console.log(that.y);  //prints y in console
            clearInterval(that.interval);
        }
   }, 10);
}

JFIDDLE

当我单击“运行”按钮时,这会按预期工作。但是当我在没有清除前一个间隔之前多次单击“运行”按钮时(当快速单击多次按钮时),间隔不会被清除并且 y 无限增加。我在这里犯了什么错误?

提前谢谢你...

【问题讨论】:

  • 想知道为什么要使用函数表达式而不是函数声明来创建构造函数。
  • @Robg 在这里使用函数表达式有什么缺点(除了在执行此行之前未定义函数)?
  • 就是这样,这里写了很多:var functionName = function() {} vs function functionName() {}。我更喜欢看到声明而不是表达式,其中表达式仅用于赋值。但其他人更喜欢在任何地方使用表达式,所以一切都是一个任务。课程用马……;-)

标签: javascript oop


【解决方案1】:

您正在创建一个全局变量 that,它会覆盖以前的 Test 实例引用:

that = this;

你应该在声明变量时使用var关键字:

var that = this;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    相关资源
    最近更新 更多