apply和call的用法总结

1、调用别的函数

function add(a,b){
  return a+b;  
}
function sub(a,b){
  return a-b;  
}
var a1 = add.apply(sub,[4,2]);  //sub调用add的方法
var a2 = sub.call(add,4,2);
alert(a1);  //6     
alert(a2);  //2

  

2、类的继承,在构造函数中继承另一个构造函数,可以将方法和属性继承过来,也可以在构造函数中继承多个其他的构造函数function Animal(name){  this.name = name;

  this.showName = function(){
        alert(this.name);    
    }    
}

function Cat(name){
  Animal.apply(this,[name]); 

} var cat = new Cat("咕咕"); cat.showName();

 

3、参数的转换,apply接受的参数是数组,像Math.max支持Math.max(param1,param2...),而不支持参数为数组,所以,可以Math.max.apply.(null, array)使用这样的方式来使max接受参数数组。

   同理,call也有类似方面的应用:Array.prototype.slice.call(arguments,0)。将arguments对象转换为数组

function test(a,b,c,d) { 
      var arg = Array.prototype.slice.apply(arguments,[1]); 
      alert(arg); 
} 
test("a","b","c","d");

/**
*使用call的方法实现
*/
function test(a,b,c,d) { 
      var arg = Array.prototype.slice.call(arguments,1); 
      alert(arg); 
} 
test("a","b","c","d");
    

  

 参考🔗https://www.cnblogs.com/dingxiaoyue/p/4948166.html

     https://www.cnblogs.com/lengyuehuahun/p/5643625.html

posted @ 2018-09-13 14:29  九萌萌  阅读(163)  评论(0编辑  收藏  举报