自调用函数中递归函数上的 setTimeout() [英] setTimeout() on recursive function within a self invoking function
问题描述
我想将我的代码作为自我调用的匿名函数分发,正如我看到的许多人所做的那样.此外,在我的代码中,我必须监视另一个库加载,以便在可用时使用它.
I want to distribute my code as a self-envoking anonymous functions, as I see many do. Also, within my code I have to monitor for another lib loading, so I can use it when it's available.
(function(window, document, undefined) {
staffHappens();
var initMyLib = function() {
if (typeof(myLib) == 'undefined') {
setTimeout("initMyLib()", 50);
} else {
useMyLib();
}
}
moreStaffHappens();
initMyLib(); //-> initMyLib is undefined
})(this, document);
这个错误是怎么发生的?initMyLib 是否应该在封闭(自调用)函数的范围内?
How can this error occur? Should initMyLib be inside the scope of the enclosing (self-envoking) function?
推荐答案
change setTimeout("initMyLib()", 50);
到 setTimeout(initMyLib, 50);
当您将字符串作为参数传递时,它会在超时触发时尝试对其进行评估,但它将在全局范围内运行.并且您的方法不存在于全局范围内.
When you pass a string as an argument it will try to evaluate it when the timeout is fired, but it will run in the global scope. And your method does not exist in the global scope.
演示在 http://jsfiddle.net/gaby/zVr7L/一个>
这篇关于自调用函数中递归函数上的 setTimeout()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!