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將數組裝換爲參數列表的集合  

相關文章
相關標籤/搜索