[英]“break” javascript execution
I was wondering if there was a way to break javascript execution, something like this 我想知道是否有办法打破 javascript执行,就像这样
<script>
if(already_done)
{
return; //prevent execution (this yields an error)
}
doSomeStuff();
</script>
I know that this is possible like this: 我知道这可能是这样的:
<script>
if(already_done)
{
// do nothing
}
else
{
doSomeStuff();
}
</script>
But it's not the solution I'm looking for. 但这不是我正在寻找的解决方案。
Hopefully this makes sense. 希望这是有道理的。
Wrap it in a function which immediately executes. 将其包装在立即执行的函数中。
(function() {
if (already_done) { return; }
doSomeStuff();
})();
FYI: return
is useless without being in a function context. 仅供参考: return
在没有功能上下文的情况下是无用的。
Also, this isn't a closure since it doesn't return an inner function which uses variables defined in an outer function. 此外, 这不是闭包,因为它不返回使用外部函数中定义的变量的内部函数。
Put your code in a closure, like this: 把你的代码放在一个闭包中,如下所示:
(function (){
if(already_done){
return;
}
doSomeStuff();
})();
It should work. 它应该工作。
You have one option directly in a <script>
block: you can throw an error, but this usually isn't desirable in the middle of a block of code... 你可以直接在<script>
块中有一个选项:你可以抛出一个错误,但这在代码块的中间通常是不可取的......
if(already_done){
throw "Uh oh";
}
What would 'already_done' be? 什么会'已经'完成? a boolean? 布尔值? it sounds to me like a loop... can you use something like?: 它听起来像一个循环...你可以使用类似的东西吗?:
While ( !already_done ) { doSomeStuff(); 而(!already_done){doSomeStuff(); } }
You could use break
with a label:
你可以使用带label:
break
label:
<script>
testcase:
if (already_done) {
break testcase; //prevent execution
}
doSomeStuff();
</script>
though, as stated in other answers, wrapping it in a function is your best method. 但是,如其他答案中所述,将其包装在函数中是最好的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.