call 與 apply 存在的意義只有一個:改變函式執行時的 this 指向。兩者效果完全相同,唯一差別在於接受參數的形式。
apply
Function.apply(obj, args)
接收兩個參數:
call
第一個參數與 apply 相同,但第二個之後是參數列表,需要一個個列出來。
在非嚴格模式下,若第一個參數傳入 null 或 undefined,函式內部的 this 會自動指向全域物件(瀏覽器環境即 window):
var test = function () { console.log(this === window); };
test.apply(null); // true
test.call(undefined); // true
1. 「借用」別人的方法
下面的例子中,foo 的 logName 被 bar 借用,this 因此指向 bar:
var foo = {
name: "mingming",
logName: function () { console.log(this.name); }
};
var bar = { name: "xiaowang" };
foo.logName.call(bar); // xiaowang
2. 實現繼承
function Animal(name) {
this.name = name;
this.showName = function () { console.log(this.name); };
}
function Cat(name) {
Animal.call(this, name);
}
var cat = new Cat("Black Cat");
cat.showName(); // Black Cat
3. 修正被意外改變的 this
實際開發中,this 指向被改變是最常見的坑之一。下面的 fun 作為普通函式呼叫,this 指向了 window,但我們真正想要的是 #test 節點:
window.id = "window";
document.querySelector('#test').onclick = function () {
console.log(this.id); // test
var fun = function () { console.log(this.id); };
fun(); // window
};
用 call 就能一行解決:
window.id = "window";
document.querySelector('#test').onclick = function () {
var fun = function () { console.log(this.id); };
fun.call(this); // test
};
另一種思路是用閉包快取 that,這在 ES5 之前非常流行:
document.querySelector('#test').onclick = function () {
var that = this;
var fun = function () { console.log(that.id); };
fun(); // test
};
而在 ES5 的嚴格模式下,普通函式呼叫時的 this 不再指向全域物件,而是 undefined:
function func() {
"use strict";
console.log(this); // undefined
}
func();
類陣列
符合以下三個條件的物件稱為類陣列:有 length 屬性、以索引方式存放資料、沒有 push / pop 等陣列方法。最常見的就是 arguments 與 NodeList。
(function () {
Array.prototype.push.call(arguments, 4);
console.log(arguments); // [1, 2, 3, 4]
})(1, 2, 3);
合併兩個陣列也是同樣思路。push 只接受 push(param1, param2, ...) 形式,透過 apply 可以把陣列「攤平」成參數列表:
var arr1 = new Array("1", "2", "3");
var arr2 = new Array("4", "5", "6");
Array.prototype.push.apply(arr1, arr2);
console.log(arr1); // ["1", "2", "3", "4", "5", "6"]
可以理解為 arr1 呼叫了 push 方法,而參數由 apply 把陣列轉換成了參數列表。
求類陣列中的最大值
(function () {
var maxNum = Math.max.apply(null, arguments);
console.log(maxNum); // 56
})(34, 2, 56);
精確判斷資料型別
console.log(Object.prototype.toString.call(123)); // [object Number]
console.log(Object.prototype.toString.call('123')); // [object String]
console.log(Object.prototype.toString.call(undefined)); // [object Undefined]
console.log(Object.prototype.toString.call(true)); // [object Boolean]
console.log(Object.prototype.toString.call({})); // [object Object]
console.log(Object.prototype.toString.call([])); // [object Array]
console.log(Object.prototype.toString.call(function () {})); // [object Function]
需要動態傳入不確定個數的參數時用 apply,參數個數固定且明確時用 call;兩者本質相同,選哪個主要看可讀性。