call(),apply()方法解析(一)

1call()apply()的作用是改变this指向,区别是传参列表不同(前者连续参数,后者为参数数组),call的性能会比apply性能要高,即快得多,原因详见https://blog.csdn.net/lengyu6220/article/details/79031507

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);

  

得到如下结果:

 

原文地址:https://www.cnblogs.com/xiaofuxuan-blogs/p/7646027.html