2013-01-11 75 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的結構做出了一個假設。