一、定义
每个函数都包含两个非继承而来的方法:call() 方法和 apply() 方法
在 javascript 中,call 和 apply 都是为了改变某个函数运行时的上下文(context)而存在的,一般来说,this总是指向调用某个方法的对象,但是使用call()和apply()方法时,就会改变this的指向
语法:
apply()
接收两个参数,一个是函数运行的作用域(this),另一个是参数数组
apply([thisObj [,argArray]])
thisObj:这个对象会代替调用apply的函数里this对象
argArray:这个是参数数组,会传递给调用apply的方法中(如果不是一个有效数组或arguments对象,会出现TypeError)
call()
call([thisObject[,arg1 [,arg2 [,...,argn]]]])
thisObj:这个对象会代替调用call的函数里this对象
argn:参数,传递给函数的参数必须列举出来
二、apply、call区别
对于 apply、call 二者而言,作用完全一样,call()和apply()的不同点就是接收参数的方式不同。
apply()方法接收两个参数,一个是函数运行的作用域(this),另一个是参数数组。
call()方法不一定接受两个参数,第一个参数也是函数运行的作用域(this),但是传递给函数的参数必须列举出来。
var func = function(arg1, arg2) {};
func.call(this, arg1, arg2);
func.apply(this, [arg1, arg2])
三、apply、call实例
//call()
function Animal(name,age){
this.name=name
this.age=age
this.say=function(){
console.log(this.name+this.age)
}
}
function Dog(name,age){
Animal.call(this,...arguments) //将数组列举出来
var dog=new Dog('doggy','3')
dog.say() //doggy3
//apply
function Cat(name,age){
Animal.apply(this,arguments)
}
var cat=new Cat('catty','2') //catty2
cat.say()
常用实例:
//获取数组中的最大值或最小值
var numbers = [1,2,3 ];
var maxNum = Math.max.apply(Math, numbers), //3
maxNum = Math.max.call(Math,...numbers); //3
var minNum = Math.min.apply(Math, numbers), //1
minNum = Math.min.call(Math,...numbers); //1
//数组合并
var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
Array.prototype.push.apply(arr1, arr2);
console.log(arr1);//[ 1, 2, 3, 4, 5, 6 ]
//定义一个 log 方法,让它可以代理 console.log 方法
function log(){
console.log.apply(console, arguments);
};
log(1,2,3) //1 2 3