2013-01-11 68 views
1

我有一个函数parent,调用child,然后做其他的东西里面otherStuff功能,使父函数返回

function parent() { 
    child(); 

    otherStuff(); 
} 

是否有可能修改child(离开parent为是),使得child呼叫部队parentchild返回后立即返回?在EcmaScript 6中这可能吗?要做到这一点

+1

返回正确*返回正确*或由于儿童错误?如果是后者,只是在孩子身上抛出异常。 – Yoshi

+0

没有修改父母,你只能抛出一个异常,并像@Yoshi所说的那样处理它。 – Lloyd

+2

也许像[** http://jsfiddle.net/yrtS2/**](http://jsfiddle.net/yrtS2/)。 –

回答

0

烂路是抛出一个例外child,这将泡高达parent,然后到原主叫方。这种方法预期原始呼叫者parent可以捕捉到异常。

function originalCaller() { 
    try { 
    parent(); 
    } 
    catch(e) {} 
} 

function parent() { 
    child(); 
    otherStuff(); 
} 

function child() { 
    throw 0; 
} 

function otherStuff() { 
    // other stuff 
} 

你想离开parent原样吧? 所以,丑陋的方式是让child临时修改otherStuff

function child() { 
    _otherStuff = otherStuff; 
otherStuff = function() { otherStuff = _otherStuff; } 
} 

这样otherStuff无助一次,然后又回到了原来的状态。再次,它不仅是完全丑陋的,而且对parent的结构做出了一个假设。