call 和 apply 都是爲了改變某個函數運行時的 context 即上下文而存在的,換句話說,就是爲了改變函數體內部 this 的指向。
call 和 apply二者的作用完全一樣,只是接受參數的方式不太一樣。
方法定義
apply
Function.apply(obj,args)方法能接收兩個參數:
obj:這個對象將代替Function類裏this對象
args:這個是數組或類數組,apply方法把這個集合中的元素作爲參數傳遞給被調用的函數。
call
call方法與apply方法的第一個參數是一樣的,只不過第二個參數是一個參數列表
在非嚴格模式下當我們第一個參數傳遞爲null或undefined時,函數體內的this會指向默認的宿主對象,在瀏覽器中則是window
var test = function(){
console.log(this===window);
}
test.apply(null);//true
test.call(undefined);//true
用法
"劫持"別人的方法
此時foo中的logName方法將被bar引用 ,this指向了bar
var foo = {
name:"mingming",
logName:function(){
console.log(this.name);
}
}
var bar={
name:"xiaowang"
};
foo.logName.call(bar);//xiaowang
實現繼承
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
在實際開發中,經常會遇到this指向被不經意改變的場景。
有一個局部的fun方法,fun被作爲普通函數調用時,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,apply我們就可以輕鬆的解決這種問題了
window.id="window";
document.querySelector('#test').onclick = function(){
console.log(this.id);//test
var fun = function(){
console.log(this.id);
}
fun.call(this);//test
}
當然你也可以這樣做,不過在ECMAScript 5的strict模式下,這種情況下的this已經被規定爲不會指向全局對象,而是undefined:
window.id="window";
document.querySelector('#test').onclick = function(){
var that = this;
console.log(this.id);//test
var fun = function(){
console.log(that.id);
}
fun();//test
}
?
function func(){
"use strict"
alert ( this ); // 輸出:undefined
}
func();
其他用法
類數組
這裏把符合以下條件的對象稱爲類數組
1.具有length屬性
2.按索引方式存儲數據
3.不具有數組的push,pop等方法
常見類數組有 arguments,NodeList!
(function(){
Array.prototype.push.call(arguments,4);
console.log(arguments);//[1, 2, 3, 4]
})(1,2,3)
這樣就往arguments中push一個4進去了
Array.prototype.push 頁可以實現兩個數組合並
同樣push方法沒有提供push一個數組,但是它提供了push(param1,param,…paramN) 所以同樣也可以通過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的用法總結的全部內容,歡迎大家積極留言參加討論,也希望本文對大家學習javascript有所幫助。
本文參考自腳本之家:http://www.jb51.net/article/89501.htm