2
我需要使用setInterval創建多個同時具有不同速度頻率的動畫對象,並使用相同的構造函數生成。我面臨的問題是,在創建2個或更多對象後,傳遞給setInterval的對象的方法始終引用最後創建的對象。貝婁是我想要達到一個例子:同時多次調用setInterval在javascript中具有相同構造函數的對象內
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。使用簡單的函數,它工作正常,但我想自己的內容動畫對象可以填充和獨立運行。謝謝。
可能的重複http://stackoverflow.com/questions/1451009/javascript-infamous-loop-problem – 2012-03-01 15:06:47