javascript - 定義function

基本function框架

  • 無輸入無輸出
function a() {
    alert('a');
}
a();    // call a function. show a
  • 有輸入無輸出
function b(input) {
    alert('b:'+input);
}
b("123");    // call b function. show b:123
  • 無輸入有輸出
function c() {
    alert('c');
    return "result";
}
var returnC = c();   // call c function. show c
  • 有輸入有輸出
function d(input) {
    alert('d:' + input);
    return input;
}
var returnD=d("input"); // call d function. show d:input
  • 階層式function定義,共用區域變數
function A1(input) {
    function B1() {
        return 'B1:'+input;
    }
    alert(B1());        // call B1 function
}
A1('input');            // call A1 function. show B1:input
try {
    B1();               // undefined exception
}
catch (e) { alert(e) };

  • 檢查Function是否存在,存在才執行:

if (typeof (customFunction) == 'function') {
    customFunction();
}

沒有留言:

橫式廣告