美文网首页
JS apply 与 call 方法

JS apply 与 call 方法

作者: 璎珞纨澜 | 来源:发表于2019-06-04 15:44 被阅读0次
  • apply方法能劫持另外一个对象的方法,继承另外一个对象的属性。
    Function.apply(obj,args)方法能接收两个参数
    obj:这个对象将代替Function类里this对象
    args:这个是数组,它将作为参数传给Function(args-->arguments)
<script type="text/javascript">  
    /*定义一个人类*/  
    function Person(name,age)  
    {  
        this.name=name;  
        this.age=age;  
    }  
    /*定义一个学生类*/  
    functionStudent(name,age,grade)  
    {  
        Person.apply(this,arguments);  
        this.grade=grade;  
    }  
    //创建一个学生类  
    var student=new Student("zhangsan",21,"一年级");  
    //测试  
    alert("name:"+student.name+"\n"+"age:"+student.age+"\n"+"grade:"+student.grade);  
</script>  

apply 方法接收的两个参数:
this: 在创建对象在这个时候代表的是student
arguments: 是一个数组,也就是[“zhangsan”,”21”,”一年级”];


测试结果
  • call 和 apply 的意思一样,只不过是参数列表不一样。
    Function.call(obj,[param1[,param2[,…[,paramN]]]])
    obj:这个对象将代替Function类里this对象
    params:这个是一个参数列表
    上述案例也可以用 call 方法替代 apply 方法: Person.call(this,name, age),效果一样。

  • 什么情况用 apply 方法,什么情况用 call 方法?
    如果参数的形式是数组的时候, 就可以采用 apply;如果参数列表直接指定参数列表对应值的位置,就可以采用 call。

  • apply 妙用:
    利用 apply 方法可以将数组集合默认转换为参数列表来使用的特性。

  1. var max=Math.max.apply(null,array) 得到一个数组中最大一项
    Math.max 参数里面不支持Math.max([param1,param2]) 也就是数组,但是它支持Math.max(param1,param2,param3…), 利用 apply 方法会将一个数组转换为一个接一个的参数传递给方法。

  2. 同理,var min=Math.min.apply(null,array) 得到一个数组中最小一项

  3. Array.prototype.push.apply(arr1,arr2); 实现两个数组合并
    push方法没有提供push一个数组,但是它提供了push(param1,param,…paramN) ,所以同样也可以通过apply来转换一下这个数组再传入 push 方法中进行合并。

vararr1=new Array("1","2","3");  
vararr2=new Array("4","5","6");  

Array.prototype.push.apply(arr1,arr2);  

博客原文参考:https://www.cnblogs.com/chenhuichao/p/8493095.html

相关文章

网友评论

      本文标题:JS apply 与 call 方法

      本文链接:https://www.haomeiwen.com/subject/aiglxctx.html