关于javascript中call()和apply()方法的总结

前段时间在使用javascript的过程中遇到了继承的问题,自己顺便就对call()和apply()方法进行了了解。

两个方法的共同之处:这两个方法作用相同,都用来改变当前函数调用的对象,即改变this的指向。

两个方法的不同之处:不同之处就是两种方法的传参方式不同,apply接受的是数组参数,call接受的是连续参数。

apply()方法的定义:

Function.apply(obj,args);

obj:这个对象会代替Function类里边所指向的this对象。

args:这是一个数组,作为参数传递给Function。

示例:

<script>

  function Intro(name,age){
    this.name=name;
    this.age=age;
    this.speak=function(){
      console.log('My name is '+this.name+'.'+' I am '+this.age+' years old.');
    }
  }

  function IntroInh(name,age){
    Intro.apply(this,arguments);
  }
  var lm=new IntroInh('LiMing',20);
  lm.speak();

</script>

 

上面的代码做了一个简单的继承应用,也展示了apply()在其中的作用。

call()方法的定义:

Function.call(obj,[param1[,param2[,…[,paramN]]]]);

obj:这个对象会代替Function类里边所指向的this对象。

params:这是一个参数列表。

示例:

<script>

  function Intro(name,age){
    this.name=name;
    this.age=age;
    this.speak=function(){
      console.log('My name is '+this.name+'.'+' I am '+this.age+' years old.');
    }
  }

  function IntroInh(name,age){

    // Intro.apply(this,arguments);
    Intro.call(this,name,age);//对比上面apply()的不同;

  }
  var lm=new IntroInh('LiMing',20);
  lm.speak();

</script>

 

这里只做一个简单的概念和应用方法的叙述,具体的项目应用还需要我们进一步的实践。

 

posted @ 2018-06-21 15:18  Monter  阅读(353)  评论(3编辑  收藏  举报