立即執行 fun,並把 fun 內部的 this 指向傳入的新 context 物件,讓同一個方法能在不同物件上重複使用。
context:傳入的物件,用來取代 fun 原本的 this。
argsArray:陣列或類陣列物件,其中的元素會被展開成個別實參傳給 fun,因此要注意順序。
行為與 apply 相同,差別只在參數寫法:call 需要一個一個分開傳。若參數個數不確定,就用 apply。
幾個常見用法:
Math.max(); // 只接受個別參數 Math.max.apply(null, array); // 把陣列展開後傳入 Array.prototype.push.apply(arr1, arr2); // 把 arr2 的元素逐一 push 進 arr1 Array.prototype.slice.call(arguments); // 在類陣列物件上使用 slice
function isArray(obj){
return Object.prototype.toString.call(obj) === '[object Array]';
} // 更可靠的型別判斷方式
回傳一個新函式,其函式體與原函式相同,但 this 永遠指向傳入的 context,且會先帶上 bind 時指定的初始參數。後續呼叫新函式時傳入的實參,會排在這些初始參數之後。
// 原本有 4 個參數
var displayArgs = function (val1, val2, val3, val4) {
console.log(val1 + " " + val2 + " " + val3 + " " + val4);
}
var emptyObject = {};
// bind 時先固定 2 個參數
var displayArgs2 = displayArgs.bind(emptyObject, 12, "a");
// 呼叫時再補上另外 2 個
displayArgs2("b", "c"); // 輸出:12 a b c
在事件處理函式中綁定 this:
var obj = {
arg1: 1,
attach: function(){
// var self = this; ← 傳統做法
$('xxx').on('click', function (event) {
console.log(this.arg1); // 不綁定時,this 會指向觸發事件的元素
}.bind(this));
}
}
用 bind 改寫 slice:
var _Slice = Array.prototype.slice; var slice = Function.prototype.call.bind(_Slice); slice(...);
bind 在 IE5~IE8 的相容處理:
if (!Function.prototype.bind) {
Function.prototype.bind = function(context) {
var self = this,
args = arguments;
return function() {
self.apply(context, Array.prototype.slice.call(args, 1));
}
}
}
另外,setTimeout 內的 this 預設指向 window/global。若類別方法需要正確的 this,用 bind 綁到該實例,比傳入 self 更乾淨。
this 是在函式「執行時」依呼叫方式綁定的:在全域函式中 this 等於 window;當函式作為某物件的方法被呼叫時,this 等於那個物件。
判斷口訣:this 與定義位置無關。執行時若有點運算子,this 就是點前面的物件;沒有則指向 window;用 new 呼叫時指向新建立的物件;一旦使用 apply/call/bind,就指向第一個參數。
/* 例 1 */
function foo() { console.log(this.a); }
var obj2 = { a: 42, foo: foo };
var obj1 = { a: 2, obj2: obj2 };
obj1.obj2.foo(); // 42,foo 由 obj2 擁有
/* 例 2 */
function foo() { console.log(this.a); }
var obj = { a: 2, foo: foo };
var bar = obj.foo; // bar 只是引用函式本身
var a = "global";
bar(); // "global",脫離物件後 this 回到 window
最後,在 HTML DOM 的事件處理器中,this 一律指向綁定該處理器的 DOM 節點。