apply()與call()

來源:互聯網
上載者:User

標籤:

apply()與call()都是都是繼承另一個對象的方法,繼承另一個對象的變數。

例:

function Person(name,age){this.age=age;this.name=name;}function student(name,age,grade){this.grade=grade;Person.apply(this,arguments);}var student =new student("xiaowu","12","三年級");alert(student.name+student.age+student.grade)

 

function Person(name,age){this.age=age;this.name=name;}function student(name,age,grade){this.grade=grade;Person.call(this,name,age);}var student =new student("xiaowu","12","三年級");alert(student.name+student.age+student.grade)

  

輸出結果都為:xiaowu12三年級

 區別:apply()當傳入的參數是數組並且順序與所調用的對象的參數順序一致。

    call()直接在指定參數的順序。

其他用法:

js中Math.max()取兩個數中較大的數,無法比較數組中最大的數,使用aplly()就可以了

var arr = new Array(2,45,6,1,97,22,1);var MaxNum = Math.max.apply(null,arr)alert(MaxNum);

輸出結果:97

 js中push()向數組的末尾添加一個或多個元素,並返回新的長度。使用apply直接添加一個數組。

 

var arr1 = new Array("xiaoming","12");var arr2 = new Array("三年級","男");Array.prototype.push.apply(arr1,arr2);alert(arr1);

輸出結果:

 

apply()與call()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.