function functionName(arg0, arg1, ..., argN) {
statements
}
一個簡單的實例:
function str(name, age){
document.write("hello my name is " + name + ". and i am " + age + " years old.");
}
str(" oliver", 23); // hello my name is oliver. and i am 23 years old.
function sum(num1, num2){
return num1 + num2;
alert("hello"); // 永遠不會執行
}
var result = sum(321, 32);
document.write(result); // 353
執行到 return 就立即停止並退出函數,因此寫在它之後的程式碼不會執行。
一個函數也可以有多個 return,依條件分支回傳不同結果:
function conp(a, b){
if (a > b){
return a;
}else if (a == b){
return "equal";
}else{
return b;
}
}
var result = conp(4, 4);
document.write(result); // equal
var result = conp(321, 4);
document.write(result); // 321
return 也可以不帶值,這時函數立即停止並回傳 undefined:
function conp(a, b){
if (a > b){
return;
document.write("bad"); // 不會執行
}else{
document.write(b);
}
}
var a = conp(33, 3);
document.write(a); // undefined
ECMAScript 函數的參數可以是任意多個、任意型別。函數體內透過 arguments 物件存取:第一個是 arguments[0]、第二個是 arguments[1],依此類推。具名參數只是提供便利,並非必要。
function greeting(){
document.write("hello " + arguments[0] + ". you look " + arguments[1] + ".");
}
greeting("oliver", "good"); // hello oliver. you look good.
搭配 length 屬性可以知道實際傳入了幾個參數:
function countArguments(){
document.write("there are " + arguments.length + " arguments here.");
}
countArguments(321, 321, 32, 32); // there are 4 arguments here.
這特性加上 if 判斷,就能做出「參數可選」的效果:
function count(){
if (arguments.length == 1){
document.write("you just have 1 arguments.");
}else{
document.write("you have many arguments.");
}
}
count(321, 321, 321); // you have many arguments.
如果定義了兩個同名函數,只有最後一個有效:
function add(){
document.write(arguments[0] + arguments[1]);
}
function add(){
document.write(arguments[0] + 100);
}
add(321, 2); // 421,第一個 add 被覆蓋掉了
想做出類似重載的效果,只能靠 arguments.length 或型別判斷自行分流。
函數是 JavaScript 中最靈活的物件。匿名函數顧名思義就是沒有名字的函數,常見的三種定義方式如下。
第一種:函數宣告(最常規)
function double(x){
return 2 * x;
}
第二種:Function 建構子
var double = new Function('x', 'return 2 * x;');
把參數與函數體當字串傳入,撰寫與除錯都不方便,還會多一次編譯,不建議使用。
第三種:函數表達式
var double = function(x) {
return 2 * x;
}
等號右邊就是一個匿名函數,建立完成後再把參照交給變數 double。
第一種就是上面的函數表達式,最為常見。
第二種是立即執行函數表達式(IIFE):
(function(x, y){
alert(x + y);
})(2, 3);
第一組括號建立匿名函數,第二組括號立刻呼叫它並傳入參數。IIFE 常用來建立獨立作用域,避免變數污染全域,也是老式模組寫法的基礎。