call 与 apply 功能是一样的,它们的区别仅在于接收参数的方式不同。
apply()方法接收两个参数:一个是在其中运行函数的作用域,别一个是参数数据。
其第二个参数可以是 Array 的实例,也可是arguments对象
如:
function sum(num1,num2) {
return num1+num2;
}
function callSum1(num1,num2) {
return sum.apply(this,arguments);
}
call()方法接收参数:第一个与apply 一样,后参数是逐个传递
sum.call(this,num1,num2);
这两个函数的作用呢,主要是可以改变调用函数的作用域
如:
function Product(name,price) {
this.name = name;
this.price = price;
if(price < 0) {
throw RangeError("price Error");
}
}
function Food(name,price) {
Product.call(this,name,price);
this.category = 'food';
}
var o = new Food('xue',11);
console.log(o.name); // 输出 xue
在 Food 函数中调用的 call 这样 Food 数据继承了 Product 作用域