函數是 JavaScript 核心,本質是 Function 類型的實例,屬引用類型,擁有屬性與方法。本文系統梳理三種聲明方式、解析器處理差異、無重載原因及 this 綁定規則。
// 1. 函數聲明(Function Declaration)
function fun(num1, num2) { return num1 + num2; }
// 2. 函數表達式(Function Expression)
var fun = function(num1, num2) { return num1 + num2; };
// 3. Function 構造器(不推薦)
var fun = new Function("n1", "n2", "return n1+n2;");
console.log(typeof fun); // "function" —— 函數聲明被提升
console.log(typeof fun2); // "undefined" —— 表達式未執行
console.log(typeof fun3); // "undefined"
function fun(n1,n2) { return n1+n2; }
var fun2 = function(n1,n2) { return n1+n2; };
var fun3 = new Function("n1","n2","return n1+n2;");
函數聲明 在代碼執行前被解析器提升至作用域頂端;函數表達式 必須等到執行到該行才被創建。這影響調用順序與條件定義函數的行為。
函數名只是指向函數對象的指標。後定義的同名函數會覆蓋前一個:
function add(a) { return a; }
function add(a,b) { return a+b; } // 覆蓋上一個
add(1); // NaN (b 為 undefined)
add(1,2); // 3
可用 arguments 或解構賦值模擬重載。
length(形參個數)、prototype、call/apply/bind 等屬性方法。typeof fn === 'function',而非 'object'。obj.method() → this 指向 obj。func() → this 指向全局對象(嚴格模式下為 undefined)。內部函數 this 不會自動指向外層 this,需用變量保存(如 self/that)或箭頭函數。new Func() → this 指向新創建的實例,原型鏈指向 Func.prototype。this 指向。掌握 Function 類型本質,是寫好 JS 進階代碼的基石。