我有一个简单的JavaScript类。通过setInterval事件调用类原型方法
该类的一个方法使用setInterval函数设置一个计时器。每次事件触发时,我想要调用的方法都是在同一个类中定义的。
问题是,我该如何将此方法作为参数传递给setInterval函数?
一次尝试是setInterval('this.showLoading(),100)。但不起作用。这个方法访问类的属性,所以我需要'this'引用。
这是示例代码:
function LoadingPicture(Id)
{
this.imgArray = null;
this.currentImg = 0;
this.elementId = Id;
this.loadingTimer = null;
}
LoadingPicture.prototype.showLoading = function()
{
if(this.currentImg == imgArray.length)
currentImg = 0;
document.getElementById(this.elementId).src = imgArray[this.currentImg++].src;
}
LoadingPicture.prototype.StartLoading = function()
{
document.getElementById(this.elementId).style.visibility = "visible";
loadingTimer = setInterval("showLoading()", 100);
}
后一种方法更普遍适用。 +1 – xtofl 2010-01-04 20:25:16
是的,取决于...我认为前者在AS3中工作,但我不记得它是否在JS中跨浏览器。后者通常是最安全的。 – 2010-01-04 20:27:08
像魅力一样工作 – Andres 2010-01-04 20:31:00