刀刀网
您的当前位置:首页call(),apply()的用法

call(),apply()的用法

来源:刀刀网
 1、call()和apply()的作用是改变this指向,区别是传参列表不同(前者连续参数,后者为参数数组)

2、方法定义:

 function.apply(thisObj[, argArray])
 function.call(thisObj[, arg1[, arg2[, [,...argN]]]]);

特别地,当没有传参数时,function.call() 相当于执行这个function

3、实例:

由于apply()和call()方法作用是一致的,因此这里以call()为例,apply()同理:


 //定义一个Car的构造函数
 function Car(name,height){
 this.name=name;
 this.height=height;
 }

 function Maserati(name,age,height,width){
 this.name=name;
 this.age=age;
 this.height=height;
 this.width=width;
 }
 可以发现这里函数2包含了函数1的所有属性,即是继承的意思
 因此函数2这里可以用call()方法改写成
 function Maserati(name,age,height,width){
 Car.call(this,name,age);//此处this就是指向Maserati,此时Maserati就拥有Car的所有属性和方法了。
 this.height=height;
 this.width=width;
 }
 var a=new Maserati("maserati",23,188,98);

得到如下结果:

显示全文