Skip to content

Instantly share code, notes, and snippets.

@tdondich
Created May 13, 2019 03:31
Show Gist options
  • Save tdondich/a916a06baa549cc23612702ead2250ce to your computer and use it in GitHub Desktop.
Save tdondich/a916a06baa549cc23612702ead2250ce to your computer and use it in GitHub Desktop.
/**
* Simple bind polyfill for environments that do not support it,
* e.g., PhantomJS 1.x. Technically, we don't need this anymore
* since native bind is now performant enough in most browsers.
* But removing it would mean breaking code that was able to run in
* PhantomJS 1.x, so this must be kept for backward compatibility.
*/
/* istanbul ignore next */
function polyfillBind (fn: Function, ctx: Object): Function {
function boundFn (a) {
const l = arguments.length
return l
? l > 1
? fn.apply(ctx, arguments)
: fn.call(ctx, a)
: fn.call(ctx)
}
boundFn._length = fn.length
return boundFn
}
function nativeBind (fn: Function, ctx: Object): Function {
return fn.bind(ctx)
}
export const bind = Function.prototype.bind
? nativeBind
: polyfillBind
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment