gpt4 book ai didi

javascript - 在javascript中使用相同的构造函数同时多次调用对象内部的setInterval

转载 作者:行者123 更新时间:2023-11-29 22:25:46 25 4
gpt4 key购买 nike

我需要使用 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 设置动画。使用简单的功能它工作正常,但我想要一个可以独立填充和运行的自内容动画对象。谢谢。

最佳答案

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

var _this = this;

应该修复它。

关于javascript - 在javascript中使用相同的构造函数同时多次调用对象内部的setInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9518351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com