Javascript 从子函数中退出

标签 javascript function parent

我有一组绑定(bind),它从代码之前和之后在函数内部获取触发器。就像下面这样:

function global() {
    before(); // call all before binds here

    //... mainFunction code...

    after(); // call all after binds here 
}

如果 before(); 回调中的函数之一想要退出或停止 global() 进一步运行,我怎样才能停止它,而不检查返回值(value)观?

最佳答案

在不检查值 return 的情况下实现此目的的唯一方法ed,是通过 throw 引发异常正在阅读 error .

function before() {
    throw new Error('Ending execution');
}
function after() {
    console.log('Have you met Ted?');
}
function global() {
    before();
    // never reaches here
    after();
}
global(); // Error: Ending execution
console.log('foo'); // not executed

如果您在某处调用了 global 并希望调用后的任何代码继续执行,则需要用 try..catch 将其包装起来,例如

function global() {
    try {
        before();
        // never reaches here
        after();
    } catch (e) {
        console.log(e); // log error. Leave this block empty for no action
    }
}
global(); // Error logged
console.log('bar'); // still executed

关于Javascript 从子函数中退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16965287/

相关文章:

delphi - Delphi 中将对象强制转换为父类

javascript - 在 Dojo 中使用 Sizzle

javascript - 如何在 JavaScript 中声明 ClassName.FunctionName.myFunction() ?

HTML + CSS - 使图像元素成为父元素?

javascript - js : accessing scope of parent class

javascript - 格式化javascript函数的正确方法

javascript - Ionic 两侧菜单模式在添加更多内容时不会自动滚动

javascript - 正在计算(数量 * 费率 = 金额),但可以通过检查元素更改

javascript - 如何选择行数据表对应的页

javascript - 检查javascript函数是否存在并执行它