JavaScript setTimeout runs fine on some object types by not others?
This might be best explained with a code example...
Object_A = {
testLoop:function(){
log("running");
setTimeout(Object_A.testLoop, 1000);
}
};
Object_B = function(){
this.testLoop= function(){
log("running");
setTimeout(this.testLoop(), 1000);
}
}
Object_A.testLoop(); // logs message to console every 1000ms, as you would expect开发者_如何学Go
var objB = new Object_B();
objB.testLoop(); // runs infinitely at once (no 1000ms interval) until "Maxium call stack size exceeded"
Why is it that the loop works fine in a static object but not in a "class-like" object that declares a generating function?
(on a sidenote: what it the correct name for these two types of object? I keep saying "satic" and "non-static" objects, but I feel like that's incorrect.)
Functions are first-class citizens in JavaScript. Given a function defined like this:
function foo()
{
return 0;
}
There is a difference between this:
var result = foo();
and this:
var result = foo;
The first one invokes the function named foo
and assigns the value returned by that invocation to result
. In this case, result
will be equal to zero.
The second one assigns result
to the function named foo
. Now, result
is not equal to zero; result
is equal to the function foo
.
Do you see the problem in your code now?
setTimeout(this.testLoop(), 1000);
should be setTimeout(this.testLoop, 1000);
as you want the function, not its return value.
change this line
setTimeout(this.testLoop(), 1000);
to
setTimeout(this.testLoop, 1000);
精彩评论