我有一个自我唤起的功能,就像这样:
(function myFunc(){
alert("do something cool");
})();
当浏览器调整大小时,我试图让它再次运行。因此我尝试了这个:
$(window).resize(function() {
myFunc();
});
浏览器报告myFunc
不存在。我已经尝试重新排序上面的,以便调整大小功能出现在之前,这仍然不起作用。
请有人能以我的方式指出(可能是非常明显的)错误吗?
我有一个自我唤起的功能,就像这样:
(function myFunc(){
alert("do something cool");
})();
当浏览器调整大小时,我试图让它再次运行。因此我尝试了这个:
$(window).resize(function() {
myFunc();
});
浏览器报告myFunc
不存在。我已经尝试重新排序上面的,以便调整大小功能出现在之前,这仍然不起作用。
请有人能以我的方式指出(可能是非常明显的)错误吗?
The syntax you've used allows the name myFunc
only to be seen inside the myFunc
function itself. It is called a named function expression.
(function myFunc() {
// myFunc can be seen and used here
})();
// but not here.
Instead, try;
function myFunc() {
alert("do something cool");
}
myFunc();
$(window).resize(function () {
myFunc();
});
A function may reference itself via arguments.callee
, however it must be done right.
window.onresize = arguments.callee;
This will work. However if you're a jQuery nut (note: I am not), you might be tempted to write this:
$(window).resize(function() {arguments.callee();});
This will fail horribly and cause an infinite loop, because at the point of being called arguments.callee
references the resize function itself.
EDIT: Upon further consideration, it wouldn't cause an infinite loop. It would error out after a moment due to a stack overflow error. Should've realised that, considering where I'm posting :p