Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active March 27, 2021 18:29
Show Gist options
  • Save WebReflection/40e68a4f603ef788121a to your computer and use it in GitHub Desktop.
Save WebReflection/40e68a4f603ef788121a to your computer and use it in GitHub Desktop.
Function.prototype.bind performance problem solved in JS … (at least for 90% of common cases without partial args)
/*jslint indent: 2 */
(function (FunctionPrototype) {
'use strict';
var originalBind = FunctionPrototype.bind;
if (!originalBind.patched) {
Object.defineProperty(
FunctionPrototype,
'bind',
{
configurable: true,
value: function bind(context) {
var callback = this;
return arguments.length === 1 ?
function () { return callback.apply(context, arguments); } :
originalBind.apply(callback, arguments);
}
}
);
FunctionPrototype.bind.patched = true;
}
}(Function.prototype));
@yubaoquan
Copy link

What is little-known edge use case for bind? Could you please make an example?

@mamacdon
Copy link

mamacdon commented Feb 9, 2017

function foo() {
   console.log(this.x);
}

var context = { x: 123 };
var boundFunction = foo.bind(context);

boundFunction();     // prints 123
new boundFunction(); // prints undefined

The edge case is the last statement. When boundFunction is called through the new operator, the receiver (this) is set to the object being created by new, not the original context object.

I'm not sure, but this behavior may've been designed to allow constructor functions to take advantage of bind's partial application without the undesired side effect of setting this. For example:

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

var festivaFactory = Car.bind(null /*doesn't matter*/, "Ford", "Festiva");
var oldCar = new festivaFactory(1989);    // {make: "Ford", model: "Festiva", year: 1989}
var newerCar = new festivaFactory(1993);  // {make: "Ford", model: "Festiva", year: 1993}

The code above would not work as intended if the bound function received this == null when invoked through new. Of course, there are other ways of achieving the same effect.

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