js 中call和apply的应用

1、方法概念

Function.prototype.call();

Function.prototype.apply();

语法:fun1.call(fun2,arg1,arg2,arg3,...);

         fun1.call(fun2,[arg1,arg2,arg3,...]); 

说明:改变fun1的this指向,即将fun2代替fun1里的this,也可以理解为fun2继承了fun1里所定义的属性和方法;

参数:arg1,arg2,...为方法的参数;

区别:call方法的参数为一一列举,apply方法的参数形式为数组;

2、应用

2.1 call引用对象的方法

function a(arg1,arg2){
      console.log(arg1+arg2);          
}    

function b(arg1,arg2){
      console.log(arg1-arg2);          
}    

a(3,1);   //4
b(3,1);   //2
a.call(b,3,1)  //4
// 说明: a.call(b,3,1) 理解为a对象的方法应用到b对象上;注意这里没有涉及this的指向

2.2 改变this的指向

function Aobj(){
    this.name="我是a";
    this.showA=function(){
    console.log(this.name)
}
}

function Bobj(){
    this.name="我是b";
    this.showB=function(){
    console.log(this.name)
}
}   
var a=new Aobj();
var b=new Bobj(); a.showA(); // 我是a; b.showB(); // 我是b; a.showA.call(b); //我是b;

/**
* 说明:a.showA.call(b); 执行的是aObj里的showA方法,但是将a.showA方法的this指向了b;
* 所以a.showA中的this.name 就是b.name 为"我是b";
*/

2.3 实现继承

function Aobj(name){
    this.name=name;
    this.showA=function(){
    console.log(this.name)
}
}

function Bobj(name){
    Aobj.call(this,name)       //将Aobj的属性和方法继承
}


var obj=new Bobj("I'm lucy");
obj.showA();  //I'm lucy 

/**
* 说明:Bobj里并没有定义任何的属性和方法;但是Aobj.call(this,name) 中将Aobj的this指向了Bobj,
* 所以Bobj里也拥有了name属性和showA方法;
*/

3 apply的应用

3.1 apply实现方法

以上案例都可用apply方法,只需将参数写成数组就好,

如:a.call(b,[3,1])  ; a.showA.apply(b); Aobj.apply(this,[name])

 

3.2 apply的巧妙用法

3.2.1 Math函数

Math.max函数使用方法:Math.max(arg1,arg2,arg3,...);    Max.min同理 

var max1=Math.max (1,3,5,7,9);
console.log(max1)  // 9;

var arr=[1,3,5,7,9];
// Math.max不支持 Math.max(arr);

// apply方法应用:
var max2=Math.max.apply(null,arr);
console.log(max2)  // 9;  

/**
*  这里传入不存在的null对象调用Math.max方法,但是并没有改变this的指向
*/

 

3.2.2 合并数组

var arr1=[1,2,3];
var arr2=[4,5,6];
var arr3=[7,8,9];

//为数组添加元素的push方法 arr1.push(arr2); console.log(arr1); // [1,2,3,[4,5,6]] 并不能实现同级合并; Array.prototype.push.apply(arr2,arr3); console.log(arr2) ;// [4,5,6,7,8,9] 利用apply实现合并数组

arr1.push.apply(arr1,arr2);
console.log(arr1) // [1,2,3,4,5,6] 利用apply实现合并数组

  

  

 

作者:龙骑士baby
         
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/xingxiangyi/p/6416425.html