JavaScript中apply的用法

apply方法: 它能劫持另一个对象的方法,继承另一个对象的属性 数组

    Function.apply(obj,args)能接受两个参数: app

        obj: 这个对象将代替Function类中的this对象
测试

        args: 这是个数组,它将做为参数传递给Function类
this

示例代码: spa

<script>
  /* 定义一我的类 */
  function Person(name, age){
    this.name = name;
    this.age = age;
  }

  /* 定义一个学生类 */
  function Student(name, age, grade){
    Person.apply(this, arguments);
    this.grade = grade;
  }

  /* 建立一个学生对象 */
  var student = new Student('LZ', 40, '一年级');

  //测试
  alert("name:"+student.name+"\n"+"age:"+student.age+"\n"+"grade:"+student.grade);

  //你们能够看到测试结果name:LZ age:40 grade:一年级
  //学生类里面我没有给name和age属性赋值啊,为何又存在这两个属性的值呢,这个就
  //是apply的神奇之处. 

</script>
分析:


    Person.apply(this,arguments); prototype

    this: 在建立对象时这个表明student
code

    arguments: 是一个数组,也就是[“LZ”,”40”,”一年级”];  对象

    用student去执行Person这个类里面的内容,在Person这个类里面存在this.name等之类的语句,这样就将属性建立到了student对象里面
继承

apply的一些其余巧妙用法 ip

    a)Math.max 能够实现获得数组中最大的一项

           由于Math.max 参数里面不支持Math.max([param1,param2]) 也就是数组

           可是它支持Math.max(param1,param2,param3…),因此能够根据刚才apply的那个特色来解决 var max=Math.max.apply(null,array),这样轻易的能够获得一个数组中最大的一项

           这块在调用的时候第一个参数给了一个null,这个是由于没有对象去调用这个方法,我只须要用这个方法帮我运算,获得返回的结果就行,.因此直接传递了一个null过去

    b)Math.min  能够实现获得数组中最小的一项

            一样和 max是一个思想 var min=Math.min.apply(null,array); 

    c)Array.prototype.push 能够实现两个数组合并

            一样push方法没有提供push一个数组,可是它提供了push(param1,param,…paramN) 因此一样也能够经过apply来装换一下这个数组,即:

            vararr1=new Array("1","2","3"); 

            vararr2=new Array("4","5","6");   

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

            也能够这样理解,arr1调用了push方法,参数是经过apply将数组装换为参数列表的集合  

相关文章
相关标签/搜索