setInterval无法按预期使用javascript oops

setInterval not working as expected with javascript oops

本文关键字:javascript oops setInterval      更新时间:2023-09-26
Js Fiddle:在此处检查

我在一个类的方法中设置了setInterval()。它在创建单个实例时工作正常,但在创建多个实例时失败。当创建了多个实例时,只有最后创建的实例工作,其他实例停止。

我的脚本如下:

function timer() {
    this.ran = Math.floor(Math.random() * 100) + 1;
    this.cls = this.ran + '_ocar';
    this.div = '<div class="' + this.cls + '">' + this.cls + '</div>';
    $('body').append(this.div);
    this.run = function() {
        thi = this;
        thi.k = 0;
        setInterval(function() {
            console.log(thi.cls);
            $('.' + thi.cls).html(thi.k++);
        }, 1000);
    }
}
one = new timer();
one.run();
setInterval(function() {
    new timer().run();
}, 5000);

thi = this;是在全局命名空间中创建的,因此每次初始化new timer()时都会被覆盖。

将其更改为var thi = this;

https://jsfiddle.net/daveSalomon/h5e8LLg3/`

我不喜欢thi作为一个var名称——它看起来像是一个拼写错误。我通常使用_this_scope

试试这个:

 function timer(){
    var thi = this;
    this.ran = Math.floor(Math.random() * 100) + 1;
    this.cls =  this.ran+'_ocar';
    this.div = '<div class="'+this.cls+'">'+this.cls+'</div>';
    $('body').append(this.div);
    this.run = function(){
       thi.k = 0;
       setInterval(function(){
         console.log(thi.cls);
         $('.'+thi.cls).html(thi.k++);
      },1000);
   }
}
one = new timer();
one.run();
setInterval(function(){
  new timer().run();
},5000)

您的变量thi需要在本地声明并移动。