javascript - 如何从内部重新启动函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2940862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript - how to restart a function from inside it?
提问by FernandoSBS
How do I restart a function calling it from inside the same function?
如何重新启动从同一函数内部调用它的函数?
回答by Nick Craver
Just call the function again, then return, like this:
只需再次调用该函数,然后返回,如下所示:
function myFunction() {
//stuff...
if(condition) {
myFunction();
return;
}
}
The ifpart is optional of course, I'm not certain of your exactapplication here. If you need the return value, it's one line, like this: return myFunction();
这if部分当然是可选的,我不确定你在这里的确切应用。如果您需要返回值,它是一行,如下所示:return myFunction();
回答by tbranyen
Well its recommended to use a named function now instead of arguments.callee which is still valid, but seemingly deprecated in the future.
好吧,它建议现在使用命名函数而不是 arguments.callee,它仍然有效,但似乎将来会被弃用。
// Named function approach
function myFunction() {
// Call again
myFunction();
}
// Anonymous function using the future deprecated arguments.callee
(function() {
// Call again
arguments.callee();
)();
回答by alex
You mean recursion?
你是说递归?
function recursion() {
recursion();
}
or
或者
var doSomething = function recursion () {
recursion();
}
NoteUsing this named anonymous function is not advised because of a longstanding bug in IE. Thanks to larkfor this.
注意不建议使用这个命名的匿名函数,因为 IE 中存在一个长期存在的错误。感谢云雀。
Of course this is just an example...
当然这只是一个例子...

