1 定义
call 方法
语法:call(thisObj,参数1,参数2,。。。参数n)。参数为当前函数的参数
定义:调用一个对象的一个方法,以另一个对象替换当前对象。
如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。
apply方法
语法:call(thisObj,[参数1,参数2,。。。参数n])
定义:应用某一对象的一个方法,用另一个对象替换当前对象。 说明:
如果 argArray 不是一个有效的数组或者不是 arguments 对象,那么将导致一个 TypeError。
如果没有提供 argArray 和 thisObj 任何一个参数,那么 Global 对象将被用作 thisObj, 并且无法被传递任何参数。
区别:apply方法将所有参数放在一个数组上。数组可换为arguments
2.常用实例
1)普通函数
function a(x,y){
return x-y;
}
function b(x,y){
return x+y;
}
console.log(a.call(b,3,4));//控制台输出-1
console.log(b.call(a,3,4));/控制台输出7
说明:用a来替换b,即a.call(b,1,2)等于a(1,2)
2)工厂函数写法
function a(x,y){
this.x=x;
this.y=y;
this.say=function(){
return this.x;
};
}
function b(x,y){
this.x=x;
this.y=y;
}
var aObj=new a(1,2);
var bObj=new b(1,2);
aObj.say.call(bObj,3,4);//通过call或apply方法,将原本属于a对象的say()方法交给对象b来使用了。
将输出返回3
3)实现继承
function a(x,y){
this.x=x;
this.y=y;
this.say=function(){
alert(this.x);
};
}
function b(x,y){
a.call(this,x,y);
}
var bObj=new b(1,2);
bObj.say();//输出1
说明:使用a对象替代了当前对象,b对象就有了a的属性和方法。b就可调用a的方法say()
4)多继承
function a(){
this.say(){
alert("这是a的方法");
}
}
function b(){
this.run=function(){
alert("这是b的方法");
}
}
function c(){
a.call(this);
b.call(this);
}
说明:c就可以用a和b的方法;
引申
1.求一个数组的最大项,最小项
Math.max()//只能传入参数值,不能传入数组
可借助apply方法:Math.max.apply(null,arr);Math.min.apply(null,arr);
2.将两个数组合并
var arr1=[1,2,3];
var arr2=[4,5,6];
Array.prototype.push.apply(arr1,arr2);