HTML and CSS Reference
In-Depth Information
Listing 6.6 bind with arguments support
if (!Function.prototype.bind) {
Function.prototype.bind = function (thisObj) {
var target = this;
var args = Array.prototype.slice.call(arguments, 1);
return function () {
var received = Array.prototype.slice.call(arguments);
return target.apply(thisObj, args.concat(received));
};
};
}
This implementation is fairly straightforward. It keeps possible arguments
passed to bind in an array, and when the bound function is called it concatenates
this array with possible additional arguments received in the actual call.
Although simple, the above implementation is a poor performer. It is likely that
bind will be used most frequently to simply bind a function to an object, i.e., no
arguments. In this simple case, converting and concatenating the arguments will
only slow down the call, both at bind time and at call time for the bound function.
Fortunately, optimizing the different cases is pretty simple. The different cases are:
Binding a function to an object, no arguments
Binding a function to an object and one or more arguments
Calling a bound function without arguments
Calling a bound function with arguments
The two latter steps occur for both of the former steps, meaning that there
are two cases to cater for at bind time, and four at call time. Listing 6.7 shows an
optimized function.
Listing 6.7 Optimized bind
if (!Function.prototype.bind) {
(function () {
var slice = Array.prototype.slice;
Function.prototype.bind = function (thisObj) {
var target = this;
if (arguments.length > 1) {
 
Search WWH ::




Custom Search