call和apply用來調用函數,並用指定對象(第一個參數)替換函數的 this 值,同時用指定數組替換函數的參數。注:也可以不指定參數,此時只是單純的調用函數,
如:fun.call()
語法:
fun.call(thisobj,arg1,arg2) ;當後面參數個數確定時用call,參數之間用逗號連接
fun.apply(thisobj,[arg1,arg2]);當後面參數個數不確定時用apply,參數通過數組形式輸入
call和apply的作用:
改變this的指向,第一個參數爲你要傳入的對象,傳入後函數的this就指向了這個對象,後面的參數爲你爲函數傳遞的參數值
簡單案例:
var str='js';
function fo(){
var str='jq';
console.log(this.str);//此時this指向window
console.log(this===window);
console.log(this===obj);
//輸出js,true,false
}
fo();
var obj={
str:'html'
};
fo.call(obj)//輸出html,false,true,這就證明了call將fo的this指向改爲了obj;
var ob={
str:'css',
}
var get=function(){
console.log(str);//js 此時讀取的是全局變量的值
console.log(this.str);//css 此時this指向了ob,返回的就是ob.str
}
get.call(ob)
複雜案例:
function log(){
var args=Array.prototype.slice.call(arguments);//將參數轉爲數組
//slice(start,end(非必須) )方法可從已有的數組中返回選定的元素。
//Javascript函數中的參數對象arguments是個對象,而不是數組。但它可以類似數組那樣通過數字下表訪問其中的元素,而且它也有length屬性標識它的元素的個數。通常我們把它轉換成數組用Array的slice函數,示例代碼如下:function fn() { var arr = Array.prototype.slice.call(arguments,0);}
//所以Array.prototype.slice.call(arguments)就是將參數轉爲數組然後返回數組
console.log(args);//Array [ "hello", "world" ]
args.unshift('(gykj)');//unshift(a,b,c)向數組的開頭添加至少一個元素
console.log(args);//Array [ "(gykj)", "hello", "world" ]
console.log.apply(console,args);//(gykj) hello world 這裏的apply可以將數組元素作爲字符參數輸出
//由於參數個數不確定這裏只能使用apply
}
log('hello','world')