HTML and CSS Reference
In-Depth Information
6.1.4 Binding with Arguments
According to the ECMAScript 5 specification (and, e.g., the Prototype.js implemen-
tation), bind should support binding functions to arguments as well as the this
value. Doing so means we can “prefill” a function with arguments, bind it to an
object, and pass it along to be called at some later point. This can prove extremely
useful for event handlers, in cases in which the handling method needs arguments
known at bind time. Another useful case for binding arguments is deferring some
computation, e.g., by passing a callback to setTimeout .
Listing 6.5 shows an example in which bind is used to prefill a function with
arguments to defer a benchmark with setTimeout . The bench function calls
the function passed to it 10,000 times and logs the result. Rather than manually
carrying out the function calls in an anonymous function passed to setTimeout ,
we use bind to run all the benchmarks in the benchmarks array by binding the
forEach method to the array and the bench function as its argument.
Listing 6.5 Deferring a method call using bind and setTimeout
function bench(func) {
var start = new Date().getTime();
for (var i = 0; i < 10000; i++) {
func();
}
console.log(func, new Date().getTime() - start);
}
var benchmarks = [
function forLoop() { /* ... */ },
function forLoopCachedLength() { /* ... */ },
/* ... */
];
setTimeout(benchmarks.forEach.bind(benchmarks, bench), 500);
The above listing will cause the benchmarks to be run after 500 milliseconds.
The keen reader will recognize the benchmarks from Chapter 4, Test to Learn .
Listing 6.6 shows one possible way of implementing bind such that it allows
arguments bound to the function as well as the this value.
 
Search WWH ::




Custom Search