ECMAScript 5 has introduced the new Function.prototype.bind() function which not only gives you the ability to natively bind a primitive or object to a function and also curry data for the function. Unfortunately, up to this point, nobody has written an implementation of this function to make it work on older browsers strictly according to the standards of this new edition. Even the implementation on MDN doesn’t work perfectly. Still, many times, I just need to bind an object to a function. That said, I came up with the following simple implementation for a similar function:


(function(slice) {
  Function.prototype.$bind = function(objThis) {
    var fnThis = this;
    var args = slice.call(arguments, 1);
    return function() {
      return fnThis.apply(objThis, args.concat(slice.call(arguments)));
    };
  };
})([].slice);

What would be a good use of this function? What about to make a shortcut for Array.prototype.slice.call() called callSlice()? Here is the one-line definition:


// Function equivalent to calling Array.prototype.slice.call().
var callSlice = [].slice.call.$bind([].slice);

Pretty cool, right? Basically, I am making sure that Array.prototype.slice is bound to the generic call() function which is available for all functions. In reality, [].slice.call was only used to get a reference to the generic call() function. After that, I am using the $bind() function to make sure that [].slice, which references Array.prototype.slice(), gets bound to the call() function.

As you might also know, the new bind() function gives you the ability to pre-fill parameters. Fortunately, our $bind() function can do the same thing:


// Gets a date object for the current time.  If the offset is specified, it
// is added to the current time as milliseconds.
function getDate(offset) {
  return new Date(+new Date + (+offset || 0));
}

// Represents an our in milliseconds.
var MS_HOUR = 1000 * 60 * 60;

// Gets the date and time for two hours ago.
var get2HoursAgo = getDate.$bind(0, -2 * MS_HOUR);
// Gets the date and time for this time tomorrow.
var getTomorrow = getDate.$bind(0, 24 * MS_HOUR);

As you can see, after creating the getDate() function, we created two more functions which call the getDate() function with the specified offsets. FYI, the first parameter to the $bind() function doesn’t matter in this case because we don’t need to bind anything in particular to the getDate() function.


1 Comment

Chris West's Blog » JavaScript – Binding To A Function · August 12, 2011 at 8:44 PM

[…] View original post here: Chris West's Blog » JavaScript – Binding T&#959 A Function […]

Leave a Reply

Your email address will not be published. Required fields are marked *