Expect the interviewer to ask about new even though the question doesn't mention it. bind returns a new function that calls the original with a fixed this and the bound arguments placed before the call's own arguments. The part the question is really about is new: when the bound function is called as a constructor, the bound this is ignored and a new instance of the original is made, with the bound arguments still applied, and instanceof against the original still works. The classic polyfill detects new with this instanceof bound and sets bound.prototype = Object.create(target.prototype); the modern one uses new.target and Reflect.construct, which also works for classes and matches native name, length and instanceof (only the missing prototype of native bound functions can't be copied).
Implement Function.prototype.bind.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
Capture this (the function being bound) and return a wrapper that calls it with apply(thisArg, [...boundArgs, ...args]). That's enough for the everyday use: passing obj.method as a callback without losing obj.
Function.prototype.myBind = function (thisArg, ...boundArgs) {const fn = this; // the function myBind was called onreturn function (...args) {// Fixed `this`, bound arguments first, then whatever the call passes.return fn.apply(thisArg, [...boundArgs, ...args]);};};
passes 3 checks run on every build, against the native method where there is one
- fixes this and prepends arguments, like native
- a method keeps its object when passed around
- the return value comes through
With new bound(), JavaScript makes a fresh object from bound.prototype and passes it as this. If this instanceof bound, use that object instead of the bound this. Setting bound.prototype = Object.create(target.prototype) makes those objects instances of the target, so prototype methods and instanceof work. Binding a bound function keeps the first this; the arguments accumulate.
Function.prototype.myBind = function (thisArg, ...boundArgs) {const target = this;if (typeof target !== 'function') throw new TypeError('Bind must be called on a function');function bound(...args) {// Called with `new`: `this` is a fresh object made from bound.prototype. Then the bound// `this` is ignored and the new object is used, as the spec requires.const calledWithNew = this instanceof bound;return target.apply(calledWithNew ? this : thisArg, [...boundArgs, ...args]);}// Objects made with `new bound()` inherit from the target's prototype, so instanceof works.if (target.prototype) bound.prototype = Object.create(target.prototype);return bound;};
passes 4 checks run on every build, against the native method where there is one
- with new, the bound this is ignored and an instance is made, like native
- methods on the prototype work on instances
- binding twice: the first this wins, arguments add up
- calling it on something that isn't a function throws a TypeError
this instanceof bound can be fooled (calling bound.call(new bound())) and apply can't call a class. new.target says exactly whether new was used, and Reflect.construct(target, args, newTarget) builds the instance the way new would, including for classes. Native bound functions are named bound f, have length reduced by the bound arguments and delegate instanceof to the target; the stage copies those, and the checks compare with native bind. One thing a polyfill can't copy: native bound functions have no prototype property (so class X extends f.bind(null) throws), but a normal function's prototype can't be deleted.
Function.prototype.myBind = function (thisArg, ...boundArgs) {const target = this;if (typeof target !== 'function') throw new TypeError('Bind must be called on a function');function bound(...args) {if (new.target) {// Reflect.construct works for classes too (they can't be called with apply). Constructing// `bound` itself means constructing the target; a subclass's new.target is passed through.return Reflect.construct(target, [...boundArgs, ...args], new.target === bound ? target : new.target);}return Reflect.apply(target, thisArg, [...boundArgs, ...args]);}// Like a native bound function: name "bound f", length reduced by the bound arguments, and// instanceof checks against the target.Object.defineProperty(bound, 'name', { value: `bound ${typeof target.name === 'string' ? target.name : ''}` });Object.defineProperty(bound, 'length', { value: Math.max(0, (Number.isInteger(target.length) ? target.length : 0) - boundArgs.length) });Object.defineProperty(bound, Symbol.hasInstance, { value: (obj) => obj instanceof target });// One difference remains: a function's prototype property can't be deleted (it isn't// configurable), so unlike a native bound function this one has one.return bound;};
passes 3 checks run on every build, against the native method where there is one
- name and length match native
- works with classes, which can't be called with apply
- an arrow function can't be constructed, bound or not
Passing methods as callbacks
button.addEventListener('click', this.save) calls save with this set to the button. this.save = this.save.bind(this) in a constructor, or an arrow function class field, was the standard fix in class-based React components.
Partial application
Binding leading arguments makes specialised functions: const logError = log.bind(null, 'error'). null is a common thisArg when this doesn't matter.
Bound constructors
Binding a constructor's first arguments (const Admin = User.bind(null, 'admin')) gives a constructor with defaults; this is the case the new handling exists for.
Ignoring
new: the boundthisis used, andnew Bound()writes fields onto the bound object instead of making an instance.Setting
bound.prototype = target.prototypedirectly: adding a method to one changes the other.Using an arrow function as the wrapper: it can't be called with
newat all.Calling a class with
apply, which throws; constructing needsReflect.constructornew.Expecting a second
bindto changethis: the first one wins.
What's the difference between call, apply and bind?
call(thisArg, a, b) and apply(thisArg, [a, b]) call the function now; bind(thisArg, a) returns a new function to call later.
Why don't arrow functions need bind?
Arrow functions don't have their own this; they use the this of where they were written, so binding them changes nothing (and they can't be constructors).
How would you write call without call or apply?
Attach the function to the object under a unique key and call it as a method: const key = Symbol(); thisArg[key] = fn; const r = thisArg[key](...args); delete thisArg[key]; return r; (wrapping primitives with Object(thisArg) first).
- tc39.es/ecma262/#sec-function.prototype.bind
- tc39.es/ecma262/#sec-bound-function-exotic-objects-construct-argumentslist-newtarget
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new.target
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/construct