obj.call(thisObj, arg1, arg2, ...);
obj.apply(thisObj, [arg1, arg2, ...]);
兩者的作用都是一致的,即把obj綁定到this.obj,這樣thisobj就會具有obj的方法和屬性,也就是obj繼承了thisobj的方法和屬性。唯一的區別是call接受一個連續參數,而apply接受的是一個數組參數。
1.基本用法:
function add(a,b){
return a+b;
}
function sub(a,b){
return a-b;
}
var a1 = add.apply(sub,[4,2]); //sub調用add的方法
var a2 = sub.apply(add,[4,2]);
alert(a1); //6
alert(a2); //2
/*call的用法*/
var a1 = add.call(sub,4,2);
2.實現繼承
var parent = function () {
this.name = "parent";
this.age = 18;
}
var child = {}
console.log(child); //object {} 空對像
parent.call(child);
console.log(child); //object {name: 'parent',age: 18}
child繼承了parent的方法和屬性。 有很多人認爲是把parent的屬性放到了child裏面,其實不是這樣。是parent的this指針改變了,指向了child。當然apply的方法也是一樣,並不是在child裏面添加了什麼,是在parent裏面,改變了this的指向。其實是執行上下文的改變。
3.apply方法的一些妙用。(在網上看了很多例子,總結一下)
3.1 判斷一個變量的類型
Object.prototype.toString.call(name)
如果是你給的name是一個obj。那麼console.log()輸出的是[object, object],如果是function,輸出的是[object, function];
3.2 Math.max和Math.min方法的使用。
因爲Math.max不支持Math.max([param1,param2...])也就是數組,但是它支持Math.max(param1, param2...),所以可以根據apply的特點來解決獲取數組最大值的問題。
var max = Math.max.apply(null,arr);這裏在調用的時候第一個參數給了null,這個是因爲沒有對象去調用這個方法,我只是用這個方法幫助運算,得到返回的結果就行。直接
傳遞一個null。用這種方法也可以實現得到數組中的最小項。
3.3 Array.prototype.push可以實現兩個數組的合併
同樣push方法沒有提供push一個數組,但是它提供了push(param1,param2,param3...paramN),同樣也可以用apply來轉換一下這個數組,即:
1.var arr1 = new Array(1,2,3);
2.var arr2 = new Array(4,5,6);
3.Array.prototype.push.apply(arr1,arr2); //得到合併後數組的長度,因爲push就是返回一個數組的長度
也可以這樣理解,arr1調用了push方法,參數是通過apply將數組轉換爲參數列表的集合,arr1就會變成合並之後的數組。