標籤: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把函數作為另一函數的參數