【问题标题】:simultaneous multiple calls to setInterval inside objects with same constructor in javascript在javascript中同时多次调用具有相同构造函数的对象内部的setInterval
【发布时间】:2012-03-01 14:52:32
【问题描述】:

我需要使用 setInterval 创建多个同时具有不同速度频率的动画对象,并由同一个构造函数生成。我面临的问题是,在创建 2 个或更多对象后,传递给 setInterval 的对象方法始终引用最后创建的对象。贝娄是我想要实现的一个例子:

function obj(s){
    this.speed = s;
    this.colors = ["FF0000","FF3300","FF6600","FF9900","FFCC00","FFFF00","FFCC00"];
    _this = this;
    this.counter = 0;

    this.genDiv = function(){
        this.div = document.createElement('div');
        this.div.style.width = 100 + "px";
        this.div.style.height = 100 + "px";
        document.body.appendChild(this.div);
        setInterval(function(){_this.div.style.backgroundColor =  "#" + _this.colors[_this.globalCounter()]}, _this.speed);
    };

    this.globalCounter = function(){
        if(this.counter <= (this.colors.length-1)){
            return this.counter++;
        }else{
            this.counter = 1;
            return 0;
        }
    };
}

window.onload = start;

function start(){
    var a = new obj(1000);
    var b = new obj(2000);
    a.genDiv();
    b.genDiv();
}

运行此代码后,两个 setIntervals 调用都只为对象 b 设置动画。使用简单的功能它工作得很好,但我想要一个可以填充和独立运行的自我内容动画对象。谢谢。

【问题讨论】:

标签: javascript object animation setinterval simultaneous-calls


【解决方案1】:

您在定义_this 时错过了var。没有它是一个全局变量,并被下一个新对象覆盖。

var _this = this;

应该修复它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-15
    • 2021-04-06
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多