call和apply的第一個實參是要調用函數的母對象,它是調用上下文,在函數體內通過this來獲得對它的引用。
例如,如果要想以對象o的方法來調用函數f,可以按如下的方式使用call和apply方法:
復制代碼 代碼如下:
f.call(o);
f.apply(o);
復制代碼 代碼如下:
o.m = f; //將f存儲為o的臨時方法
o.m(); //調用這個臨時方法
delete o.m; //將這個臨時方法刪除
復制代碼 代碼如下:
function testFun(){
return this.a + this.b;
}
var o = {a:1, b:2};
testFun.call(o); //3
testFun.apply(o); //3
復制代碼 代碼如下:
var a = 10, b = 20;
function testFun(){
return this.a + this.b;
}
testFun.call();
testFun.apply();
復制代碼 代碼如下:
f.call(o, 1, 2);
復制代碼 代碼如下:
f.apply(o, [1, 2]);
復制代碼 代碼如下:
function testFun(x, y){
return this.a + this.b + x + y;
}
var o = {a:1, b:2};
testFun.call(o, 10, 20);
testFun.apply(o, [10, 20]);
新聞熱點
疑難解答
圖片精選