bind Function

Datetime:2016-08-22 23:03:06          Topic: JavaScript           Share

We oftentimes assume that "native" APIs within the browser are fast -- at least faster than shims we create or have been using.  I was surprised to recently read this StackOverflow thread which asserts that Function.prototype.bind is much slower than what you can shim.  The thread cites JS Perf links (which unfortunately don't work at the moment) but assuming the statements about speed are correct, let's check out how we can create our own bind function.

JavaScript bind Function

Creating a basic bind function is incredibly easy, as the aforementioned provided:

function bind (fn, ctx) {
    return function bound () {
        return fn.apply(ctx, arguments);
    };
}

// Usage:
bind(this.someFunction, this);

This is the simplest possible bind function but it doesn't accommodate for additional arguments you can provide to bind , which is why a more complete function is more complicated:

function bind (fn, ctx/* , arg1, arg2 */) {
  return (function (prependedArgs) {
    return function bound () {
      // Concat the bound function arguments with those passed to original bind
      var args = prependedArgs.concat(Array.prototype.slice.call(arguments, 0));
      return fn.apply(ctx, args);
    };
  })(Array.prototype.slice.call(arguments, 2));

// Usage
// anotherArg is first arg to onClick, then the event
bind(this.onClick, this, anotherArg);

This more complete method merges the passed-in arguments with the arguments provided to the individual function call (an Event , for example, if bind was used on an click event).

I cannot tell you with any certainty that Function.prototype.bind is in fact super slow, and if so, it's across every browser.  It is interesting, however, to explore these native API speeds in an effort to make our apps as fast as possible.

Know more about bind speed?  Please share!





About List