JavaScript把函數作為另一函數的參數

來源:互聯網
上載者:User

標籤:ons   apply   存在   asc   結束   var   nbsp   排序   ...   

 首先說一下這個問題是怎麼產生的:今天看排序演算法,想要比較不同的排序演算法的時間花費。

最簡單的時間統計方法是在程式塊開始和結束時分別計時,求一下時間差就能得出該段代碼的耗時。

如:

var foo = function (a, b) {    return a + b}var t1 = new Date()foo(1, 2)console.log("cost time:", new Date() - t1)

但是這樣有個缺點就是,每測試一個函數,都要寫一遍

var t1 = new Date().......console.log("cost time:", new Date() - t1)

於是就想寫一個函數,可以對被調用的函數效能進行測試。

var foo = function () {    console.log("foo")}var timer = function (bar) {    var t1 = new Date()    var res = bar()    console.log("cost time:", new Date() - t1)    return res}timer(foo)

但是這樣存在一個問題,如果foo本身是攜帶參數的,我們該如何傳入它的參數呢?

var foo = function (a, b) {    console.log(a + b)}var timer = function () {    var t1 = new Date()    var res = this.apply(null, arguments)    console.log("cost time:", new Date() - t1)    return res}timer.call(foo, 1, 2)

其中,call裡面第一個參數就是我們要調用的函數,後面的參數就是對應被調函數的參數。這樣就實現了函數作為另一函數的參數的功能!

 

JavaScript把函數作為另一函數的參數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.