JavaScript 常見幾種function方式:


function jsutDo(...){}

function getSomething(){ ... return somthing;}

function doWithArg(arg){
    // use arg
}

function doWithArg(arg1, arg2){
    // use arg1 or arg2
}

Function多載?

log(f1("one",2,0.78,{},[]));
function f1(){
    debugger;
}
輸入arguments 會發現參數帶入"one"、2、0.78、{object}{}、{array}[]


Method

var ops = function addNumbers(n1,n2){
        return n1+n2;
    }
};
var x = ops.add(3,5)   //x==8
var y = ops.addNumbers(3,5) //not valid


Function in function

inner function 不能直接被呼叫
function outerFunction(n){
    function innerFunction(){
        return n*n;
    }
}
var x = outerFunction(4); //x == 16


Immediate Functions

(function() {...}());
or
(function() {...})();


Module Pattern

因為回傳的為物件,故可以直接呼叫getHiddenYear方法。
var mod = (function(){
    var m =2000,c=0,d=10,y=2;
    return{
        getHiddenYear : function(){
            return m+c+d+y;
        }
    }
}());
var x = mod.getHiddenYear(); //x ==2012


其他範例一:

function add(n1, n2){
    return n1 + n2;
}

function calc(n1,n2, processForCalc){
    return processForCalc(n1,n2);
}

function executeNath(){

    setOutput(calc(4,4,add));
}


Array:

var x = [];

var fruit = ["apple","orange","banana","strawbery","cherry"];
fruit .push("pear");  //push
fruit.pop(); //pop
fruit.sort(); //sort

var vegetables = ["carrot","broccoli","cauliflovd"];
fruit = fruit.concat(vegetable); //連接字串
fruit.slice(0,1); //index 0 -> index 1  will print apple
fruit.slice(1,2); //index 1 -> index 2  will print orange
fruit.slice(1,2,"melon","grape"); // will print apply,melon,grape,strawberry,cherry

fruit = fruit.map(function (i) {return i.toUpperCase();} ); //will print upper case;

fruit = fruit.filter(function (i) {return i[0] ===  "a" ;} ); //will print apply

fruit.every(function (i) {return i[0]==="a"}) //false 不是每個開頭都是a
fruit.every(function (i) {return i.length > 0}) //true 每個字串長度都>0

fruit.some(function (i) {return i.length > 0}) //true 部份字串長度都>0
fruit.some(function (i) {return i[0]==="a"}) //true 部份開頭都是a

fruit.forEach(function(i){

});

Object

var dog = {};
dog.breed = "German Shepherd";
dog.bark = function () {log("woof")};

var dog = {
    breed: "German Shepherd";
};


註記:
The variable in javascript are weakly-typed
截錄自MVA : developing in HTM5 with JavaScript and CSS3 Jump Start