JavaScript 中函數是「一等公民」,既可作為值傳遞、賦值給變量、作為參數傳遞,也可作為返回值。本文通過示例系統講解函數聲明、函數表達式、調用模式、引用特性及 this 綁定規則。
// 函數聲明:提升,可在聲明前調用
function show() {
document.write("show函數被調用
");
return 10;
}
// 函數表達式:不提升,必須先定義再使用
var show2 = function () {
document.write("show2函數被調用
");
return 20;
};
var hello = show(); // 調用 show(),返回值 10 賦給 hello
document.write(hello + "
"); // 10
var hello2 = show; // 將函數對象本身賦給 hello2(不調用)
document.write(hello2 + "
"); // 輸出函數源碼字符串
hello2(); // 等同於 show(),輸出 "show函數被調用" 並返回 10
function modify(obj, arr, primitive) {
obj.name = "changed"; // 影響外部
arr.push(99); // 影響外部
primitive = 999; // 不影響外部
obj = { name: "new" }; // 不影響外部(重新綁定局部變量)
}
var o = { name: "orig" };
var a = [1,2];
var p = 10;
modify(o, a, p);
console.log(o.name); // "changed"
console.log(a); // [1,2,99]
console.log(p); // 10
| 模式 | 代碼形式 | this 指向 | 備註 |
|---|---|---|---|
| 函數調用 | func() | 全域對象(瀏覽器為 window) 嚴格模式為 undefined | 最常見錯誤來源 |
| 方法調用 | obj.method() | obj | 調用表達式左側的對象 |
| 構造器調用 | new Func() | 新創建的實例對象 | 若無返回對象,自動返回 this |
| apply/call/bind | func.call(ctx, ...) | ctx(第一個參數) | 顯式綁定 |
| 箭頭函數 | () => {} | 詞法作用域的 this(定義時外層 this) | ES6,無自身 this |
var obj = {
name: "Tom",
say: function () { console.log(this.name); }
};
obj.say(); // "Tom" — 方法調用
var fn = obj.say;
fn(); // undefined / "window" — 函數調用,this 丟失
// 修復方案
var bound = obj.say.bind(obj);
bound(); // "Tom" — 硬綁定
// 或箭頭函數 (ES6)
var arrow = () => obj.say();
arrow(); // "Tom" — 詞法綁定
(function () {
var privateVar = "secret";
window.getSecret = function () { return privateVar; };
})();
// 建立私有作用域,避免汙染全域
bind、箭頭函數或 var self = this 修復。掌握函數本質與 this 機制,是寫出健壯 JavaScript 代碼的關鍵。