JavaScript 的函式同時是物件,可以賦值給變數、當參數傳遞。但比這更關鍵的是:同一個函式用不同方式呼叫,this 的指向完全不同。這是面試與除錯中的高頻考點。
function func1(...) { ... } // 函式宣告
var func2 = function (...) { ... }; // 函式表達式
var func3 = function func4(...) { ... }; // 具名函式表達式
var func5 = new Function(); // 建構子形式
函式作為物件屬性被呼叫時,this 綁定到該物件。
var myObject = {
name: "myObject", value: 0,
increment: function (num) {
this.value += typeof(num) === 'number' ? num : 0;
return this;
},
toString: function () {
return '[Object:' + this.name + ' {value:' + this.value + '}]';
}
};
alert(myObject.increment(10).increment(20).toString());
// [Object:myObject {value:30}]
回傳 this 讓方法可以串鏈呼叫,這是這個模式常見的用法。
不屬於任何物件的函式被直接呼叫時,this 綁定到全域物件(嚴格模式下為 undefined)。這被視為語言設計上的缺陷——內部函式中的 this 無法繼承外部函式的 this。
解法是在外部函式中先把 this 存起來:
getInfo: function () {
var self = this; // 保存 this
return (function () {
// return this.toString(); // 錯:this 指向 window
return self.toString(); // 對:透過 self 存取
})();
}
這個 var self = this 或 var that = this 的寫法,在 ES2015 之前是每個前端工程師都寫過的。有了箭頭函式之後,因為箭頭函式沒有自己的 this、會沿用外層的 this,這個技巧已不再是必需。
函式前加 new 呼叫時,會建立一個隱含連結到該函式 prototype 的新物件,this 綁定到這個新實例。
function MyObject(name) {
this.name = name || 'MyObject';
this.value = 0;
this.increment = function (num) {
this.value += typeof(num) === 'number' ? num : 0;
};
this.toString = function () {
return '[Object:' + this.name + ' {value:' + this.value + '}]';
};
this.target = this;
}
MyObject.prototype.getInfo = function () { return this.toString(); };
var myObject = new MyObject();
myObject.increment(10);
alert(myObject.value); // 10
alert(myObject.target === myObject); // true
JavaScript 是基於原型的語言,沒有 class 這個概念(ES2015 的 class 只是語法糖)。new 的關鍵作用就是建立原型鏈並設定 this。
apply 能手動指定 this,接受兩個參數:第一個是要綁定的物件,第二個是參數陣列。
function getInfo() { return this.toString(); }
var myObj = new MyObject();
alert(getInfo.apply(myObj)); // this 指向 myObj
alert(getInfo.apply(window)); // this 指向 window
call 的用法相同,差別在參數是直接列舉而非陣列。bind 則回傳一個 this 已綁定的新函式,適合用於回呼。
function func(a, b) {
alert(a); // 1
alert(b); // 2
for (var i = 0; i < arguments.length; i++) alert(arguments[i]); // 1,2,3
}
func(1, 2, 3);
arguments 像陣列但不是陣列,保存實際傳入的參數。它有 length 屬性表示實際個數,也有 callee 屬性可引用當前執行的函式(在匿名遞迴時有用)。
注意 arguments.length 與 func.length 不同:前者是呼叫時的實際參數個數,後者是宣告時的形參個數。
另外兩個規則:傳入參數多於宣告時,多的會被忽略;少於宣告時,缺的會被自動賦值 undefined。以 function 語句宣告的函式不能出現在迴圈或條件式中,但函式表達式可以出現在任何表達式位置。
ES2015 的 rest 參數 function func(...args) 可以取代 arguments,而且它是真正的陣列,能直接用 map、filter 等方法。