简体   繁体   English

使用“类”成员函数作为setInterval()的参数

[英]Using a “Class” member function as a Parameter for setInterval()

In Javascript is it possible to pass a member function into the function setInterval(). 在Javascript中,可以将成员函数传递到函数setInterval()中。 Hope this makes sense, I'll show you a code example of what I want to do because it's easier to explain that way. 希望这是有道理的,我将向您展示我想做的代码示例,因为这样更容易解释。

I want to call the following function every 10 milliseconds & be able to access & alter the class member this.myArray() within that function(every time the function is called). 我想每10毫秒调用一次以下函数,并且能够访问和更改该函数内的类成员this.myArray()(每次调用该函数)。

function myClass()
{
    this.myArray = new Array()
    setInterval(this.slideLoop, 10);
}

// THE WHOLE POINT OF ALL THIS IS SO I CAN ACCESS THE ARRAY this.myArray()    
// INSIDE THE FOLLOWING FUNCTION WHEN ITS CALLED FROM setInterval() EVERY 10ms
myClass.prototype.slideLoop = function()
{
    alert( this.myArray[0] );
    this.myArray.slice(0,1);
}

You can use a closure with something like 您可以将闭包与类似

function myClass()
{
    this.myArray = new Array()
    var that = this;
    setInterval(function() { that.slideLoop() }, 10);
}

For an example, see: http://jsfiddle.net/3gyXF/ 有关示例,请参见: http : //jsfiddle.net/3gyXF/

(For the example I changed the timeout to 1s and the slice to splice to illustrate) (在示例中,我将超时更改为1s,并slicesplice以进行说明)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM