自调用函数内的递归函数上的 setTimeout()
我想将我的代码作为自调用匿名函数分发,正如我看到的许多人所做的那样。另外,在我的代码中,我必须监视另一个库的加载,这样我就可以在它可用时使用它。
(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 应该在封闭(自调用)函数的范围内吗?
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);
How can this error occur? Should initMyLib be inside the scope of the enclosing (self-envoking) function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将
setTimeout("initMyLib()", 50);
更改为setTimeout(initMyLib, 50);
当您传递一个字符串作为参数时,它会尝试在以下情况下对其求值:超时被触发,但它将在全局范围内运行。并且您的方法不存在于全局范围内。
演示位于 http://jsfiddle.net/gaby/zVr7L/
change
setTimeout("initMyLib()", 50);
tosetTimeout(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.
Demo at http://jsfiddle.net/gaby/zVr7L/
您还可以使用真正的匿名函数来避免范围问题:
You could also use a real anonymous function to avoid scoping issues:
尝试阅读此答案以获取一些线索:递归函数与 setInterval 与 setTimeout javascript
这是该答案的代码示例:
Try reading this answer for some clues: recursive function vs setInterval vs setTimeout javascript
This is the code sample from that answer: