JavaScript 的call 與 apply

有這樣一段代碼:javascript

Array.prototype.concatAll = function() {
	var results = [];
	this.forEach(function(subArray) {
		results.push.apply(results, subArray);
	});

	return results;
};

其中有apply那句不是很理解,因而查了一下相關資料,瞭解了些許:java

關於apply/call

此函數的原型爲:app

fun.apply(thisArg, [argsArray])

主要做用是改變apply前面的函數執行的上下文環境。能夠粗暴的理解爲——將fun函數執行的主體改變爲thisArg。例如:函數

a.fun.apply(b, [arg1, arg2]);

基本等價於:this

b.fun(arg1, arg2);

因而上述的那個語句等價於:prototype

Array.prototype.push.apply(results, subArray);

上面簡化了Array.prototype 爲results,少寫了一個單詞。code

而push函數的定義爲:ip

arr.push(element1, ..., elementN)

而apply剛好能夠將一串參數變爲一個Array參數做爲總體傳給push函數。 因此使用apply是一個trick,使得一個Array作push操做時,能夠接收另外一個Array做爲參數。element

相關文章
相關標籤/搜索