標籤:wan foo 方式 用法 str efi 實現 ima 存在
call 和 apply 都是為了改變某個函數運行時的 context 即上下文而存在的,換句話說,就是為了改變函數體內部 this 的指向。
call 和 apply二者的作用完全一樣,只是接受參數的方式不太一樣。
方法定義
apply
Function.apply(obj,args)
方法能接收兩個參數:
obj:這個對象將代替Function類裡this對象
args:這個是數組或類數組,apply方法把這個集合中的元素作為參數傳遞給被調用的函數。
call
call方法與apply方法的第一個參數是一樣的,只不過第二個參數是一個參數列表
在非strict 模式下當我們第一個參數傳遞為null或undefined時,函數體內的this會指向預設的宿主對象,在瀏覽器中則是window
//在非strict 模式下當我們第一個參數傳遞為null或undefined時,函數體內的this會指向預設的宿主對象,在瀏覽器中則是windowvar test = function(){ console.log(this===window);}test.apply(null);//truetest.call(undefined);//true
用法
1."劫持"別人的方法(個人感覺也是繼承)
//此時foo中的logName方法將被bar引用 ,this指向了barvar foo = { name:"mingming", logName:function(){ console.log(this.name); }}var bar={ name:"xiaowang"};foo.logName.call(bar);//xiaowang
2.實現繼承
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
js中的apply與call的用法與區別