JavaScript中有一个call方法和apply方法,他们的作用基本相同,但也有略微的区别。apply()接收两个参数,一个是函数运行的作用域(this),另一个是参数数组。call()方法第一个参数与apply()方法相同,但传递给函数的参数必须列举出来 。
/*动物 */
function Animal(){
this.name='Amimal';
this.showName=function(){
alert(this.name);
};
}
/* 猫*/
function Cat(){
this.name='cat';
}
var animal=new Animal;//创建动物对象
var cat=new Cat;//创建猫对象
animal.showName.call(cat,'','');//输出cat,说明showName函数的当前this已经变为cat了
animal.showName.apply(cat,[]);//输出cat
<pre name="code" class="javascript">//call函数和apply函数的区别是call 的语法是function.call(obj,param1,param2……);applay的语法是function.call(obj,[]/*params[]参数数组*/);