簡體   English   中英

如何從Javascript中的另一個函數調用函數?

[英]How to invoke a function from another function in Javascript?

我有一個不工作的代碼。 我認為它只需要一些mods它應該工作。 我無法理解。 剛開始學習JS。

var add = function (a, b) {
    if (typeof a !== 'number' || typeof b !== 'number') {
        throw {
            name: 'TypeError',
            message: 'add needs numbers'
        }
    }
    return a + b;
}

var try_it = function (a, b) {
    try {
        add(a, b);
    } catch (e) {
        document.writeln(e.name + ': ' + e.message);
    }
}

document.writeln(try_it(2, 7));

它不起作用。 我收到“未定義”錯誤。 但是,如果我直接調用函數添加...

 var add = function (a, b) {
    if (typeof a !== 'number' || typeof b !== 'number') {
        throw {
            name: 'TypeError',
            message: 'add needs numbers'
        }
    }
    return a + b;
}

var try_it = function (a, b) {
    try {
        add(a, b);
    } catch (e) {
        document.writeln(e.name + ': ' + e.message);
    }
}

document.writeln(add(2, 7));

......我得到了理想的結果。 函數try_it一定有問題嗎?

這是因為你的try_it()沒有返回值,而你的add()是。

嘗試這樣的事情:

var try_it = function (a, b) {
    var result;  // storage for the result of add()
    try {
        result = add(a, b); // store the value that was returned from add()
    } catch (e) {
        document.writeln(e.name + ': ' + e.message);
    }
    return result;   // return the result
}

這將返回add()的結果。 undefined因為當未指定時,這是默認返回值。

編輯:更改它以將結果存儲在變量中而不是立即返回。 這樣你仍然可以捕獲錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM