DIV CSS 佈局教程網

JavaScript 如何中止函式執行:return 與返回值判斷
編輯:JavaScript綜合知識     

「終止函式執行」看似簡單,但牽涉到巢狀呼叫時就容易出錯。分兩種情況來看。

情況一:直接終止當前函式

用 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 攔下——後者語意明確,適合真正的錯誤情境,不建議用來做正常流程控制。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved