我想将我的代码分发为一个自我唤起的匿名函数,正如我看到的那样。此外,在我的代码中,我必须监视另一个lib加载,所以我可以在它可用时使用它。
(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应该在封闭(自我调用)函数的范围内吗?
答案 0 :(得分:11)
将setTimeout("initMyLib()", 50);
更改为setTimeout(initMyLib, 50);
当您将字符串作为参数传递时,它将尝试在触发超时时对其进行评估,但它将在全局范围内运行。并且您的方法不存在于全局范围内。
答案 1 :(得分:2)
尝试阅读此答案以获取一些线索:recursive function vs setInterval vs setTimeout javascript
这是该答案的代码示例:
/*
this will obviously crash... and all recursion is at risk of running out of call stack and breaking your page...
function recursion(c){
c = c || 0;
console.log(c++);
recursion(c);
}
recursion();
*/
// add a setTimeout to reset the call stack and it will run "forever" without breaking your page!
// use chrome's heap snapshot tool to prove it to yourself. :)
function recursion(c){
setTimeout(function(c){
c = c || 0;
console.log(c++);
recursion(c);
},0,c);
}
recursion();
// another approach is to use event handlers, but that ultimately uses more code and more resources
答案 2 :(得分:1)
您还可以使用真正的匿名函数来避免范围问题:
(function() {
if(typeof(myLib) == 'undefined')
setTimeout(arguments.callee, 50);
else
// loaded
})()