Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Polyfill for Function.prototype.bind
Function.prototype.bind=Function.prototype.bind||function(b){if(typeof this!=="function"){throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");}var a=Array.prototype.slice,f=a.call(arguments,1),e=this,c=function(){},d=function(){return e.apply(this instanceof c?this:b||window,f.concat(a.call(arguments)));};c.prototype=this.prototype;d.prototype=new c();return d;};
@dsingleton

This comment has been minimized.

Copy link
Owner Author

@dsingleton dsingleton commented Oct 25, 2011

Implementation taken from: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind (slightly adapted)

Compressed with http://www.refresh-sf.com/yui/

It's pretty widely supported on modern desktop browsers + many JS libraries patch it themselves. I required this to patch missing support on iOS.

@Daniel-Hug

This comment has been minimized.

Copy link

@Daniel-Hug Daniel-Hug commented May 31, 2013

For extra smallness, here are a few "clean" (JSHint friendly) optimizations :)

  • Array.prototype.slice can be replaced with []. -saves 19 characters
  • The second Function.prototype.bind can be replaced with (function(){}).bind. -saves 4 characters
  • The function expression ,c=function(){}, located in a comma separated list of variable declarations can be replaced with a function declaration (function c(){}), if it is placed before the variable declarations. -saves 1 character

See my fork: https://gist.github.com/Daniel-Hug/5682738

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment