Skip to content

Instantly share code, notes, and snippets.

@MiguelCastillo
Last active May 28, 2023 12:20
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save MiguelCastillo/38005792d33373f4d08c to your computer and use it in GitHub Desktop.
Save MiguelCastillo/38005792d33373f4d08c to your computer and use it in GitHub Desktop.
Bind polyfill
/**
* Function bind polyfill
* https://github.com/ariya/phantomjs/issues/10522
*/
if (!Function.prototype.bind) {
Function.prototype.bind = function (context /* ...args */) {
var fn = this;
var args = Array.prototype.slice.call(arguments, 1);
if (typeof(fn) !== 'function') {
throw new TypeError('Function.prototype.bind - context must be a valid function');
}
return function () {
return fn.apply(context, args.concat(Array.prototype.slice.call(arguments)));
};
};
}
@Mark-Simulacrum
Copy link

On this line, why do you put parentheses around the fn variable? I've seen that before, but always wondered what the purpose is.

@MiguelCastillo
Copy link
Author

It's more a visual thing than a function thing... I like how it reads.

@Mark-Simulacrum
Copy link

Why do you concatenate an empty array with args and Array.prototype.slice.call(arguments), instead of doing args.concat(Array.prototype.slice.call(arguments))? Also, I feel like it might be more efficient/faster to do Array.prototype.slice.call(arguments) once, and then get the args from that.

@MiguelCastillo
Copy link
Author

I could do args.concat(Array.prototype.slice.call(arguments)). It's just what I typed... 😄

You mean to do Array.prototype.slice.call(arguments) outside of the anonymous function I return? It's key concat both, the args from the call to bind and the args coming into the anonymous function. That's is because you need to handle code like fn.apply.bind where the call to bind gets its own arguments and the callback also gets its own arguments. Or maybe I misunderstood your suggestion.

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