call 和 apply 都是为了改变某个函数运行时的 (环境)context 即上下文而存在的,换句话说,就是为了改变函数体内部 this 的指向。
call, apply都属于Function.prototype的一个方法,所以每个Function对象实例,也就是每个方法都有call,apply属性
相同点:两个方法产生的作用是完全一样的。
不同点:方法传递的参数不同call()接受的是一个参数列表,而apply()接受一个参数数组。
func.call(this, arg1, arg2);
func.apply(this, [arg1, arg2]);
下面在控制台练一下:
function wo(height,age){
this.height=height;
this.age=age;
}
function erzi(height,age,weight){
wo.apply(this,arguments);
this.weight=weight;
}
var trueSon= new erzi("100cm","10","50kg");
console.log("我的儿子身高:"+trueSon.height+"我儿子年纪:"+trueSon.age+"我儿子体重:"+trueSon.weight)
function add(i, m){
return i+m;
}
function sub(i, m){
return i-m;
}
add(5,3); //8
add.call(sub, 5, 3); //8
add.apply(sub, [5, 3]); //8
//看起来可能不好理解,可以这样记,call和apply后面的函数要用前面函数的方法,简称后用前
sub(5, 3); //2
sub.call(add, 5, 3); //2
sub.apply(add, [5, 3]); //2