「終止函式執行」看似簡單,但牽涉到巢狀呼叫時就容易出錯。分兩種情況來看。
用 return 即可。
function testA() {
alert('a');
alert('b');
alert('c');
}
testA(); // 依序彈出 a、b、c
在 b 之前加上 return:
function testA() {
alert('a');
return;
alert('b'); // 不會執行
alert('c'); // 不會執行
}
testA(); // 只彈出 a
這是最容易誤解的地方。
function testC() {
alert('c');
return;
alert('cc');
}
function testD() {
testC();
alert('d');
}
testD();
我們看到 testD 中呼叫了 testC,在 testC 中想透過 return 把 testD 也終止了,事與願違——return 只終止了 testC,程式執行會依序彈出 'c'、'd'。
要達到目的,得讓呼叫方檢查返回值:
function testC() {
alert('c');
return false;
alert('cc');
}
function testD() {
if (!testC()) return;
alert('d');
}
testD(); // 只彈出 c
兩個函式都做了修改:testC 中回傳 false,testD 中對 testC 的回傳值做判斷,這樣終止 testC 的同時也能將 testD 終止。
return 的作用範圍永遠只有「當前這個函式呼叫」,它不會、也不該影響呼叫者。想要跨層中止,只有兩條路:一是如上所示用回傳值溝通,二是直接 throw 例外並由外層以 try/catch 攔下——後者語意明確,適合真正的錯誤情境,不建議用來做正常流程控制。