2013-10-16 31 views
0

如果我在函数里面调用另一个函数,怎么退出主/父函数?函数里面的函数,如何退出主函数

e.g:

function(firstFunction(){ 
    //stuff 
    secondFunction() 
    // stuff if second function doesnt exit 
} 

function secondFunction(){ 
    if(// some stuff here to do checks...){ 
     /***** Exit from this and firstFunction, i.e stop code after this function call from running ****/ 
    } 
} 
+0

你不这样做,没有解决办法的一点点。没有直接的方法。 –

回答

1

你可以返回一些值,以指示要从firstFunction()退出。

例如

function(firstFunction(){ 
    //stuff 
    rt = secondFunction() 
    if (rt == false) { 
     return; // exit out of function 
    } 
    // stuff if second function doesnt exit 
} 

function secondFunction(){ 
    if(// some stuff here to do checks...){ 
     /***** Exit from this and firstFunction, i.e stop code after this function call from running ****/ 
     return false; 
    } 
    return true; 
} 
+0

这是一个体面的方式。 –

+0

请注意,如果'secondFunction'中没有'return true',则将返回'undefined',这意味着'!rt'将始终为真,并且'firstFunction'将始终退出。 –

+0

感谢您的建议,编辑了一下。 – TheOnly92

1

您不能直接返回控制流两步上升堆栈。但是,您可以从内部函数返回一个值,然后在外部处理该值。事情是这样的:

function(firstFunction(){ 
    var result = secondFunction() 
    if (!result) 
     return 
} 

function secondFunction(){ 
    if(/* some stuff here to do checks */){ 
     return false; 
    } 
    return true; 
} 
2

其他的答案是显然是正确的,但我会略有不同,这样来做...

function firstFunction() { 
    if (secondFunction()) { 
     // do stuff here 
    } 
} 

function secondFunction() { 
    if (something) { 
     return false; // exit from here and do not continue execution of firstFunction 
    } 
    return true; 
} 

这只是一个在真正的编码风格不同意见者,并且对最终结果没有影响。

1

你应该做一个回调是这样的:

function firstFunction() { 
    secondFunction(function() { 
    // do stuff here if secondFunction is successfull 
    }); 
}; 

function secondFunction (cb) { 
    if (something) cb(); 
}; 

这种方式,你可以做asyncronous东西在secondFunction太像AJAX等

+0

+1的替代方法。我想不出为什么我会使用它,但我喜欢它:D – Archer