setInterval 未按预期工作 javascript 哎呀

setInterval not working as expected with javascript oops

Js Fiddle : check here

我在 class 的方法中设置了 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 需要在本地声明并移动。