This one looks trivial until the interviewer asks "what is this inside your myBind?" If you can answer that without hesitating, the rest writes itself.
bind returns a new function. When that new function runs later, it calls the original with a fixed this and any arguments you pinned up front, followed by whatever you pass at call time.
Function.prototype.myBind = function (context, ...bound) {
const fn = this; // the function myBind was called on
return function (...args) {
return fn.apply(context, [...bound, ...args]);
};
};Two things to say out loud while writing it:
this is the original function. greet.myBind(...) calls myBind with this === greet. Capture it as fn before you return, because inside the returned function this means something else entirely.myBind come first, then the ones passed when the bound function actually runs. That's what makes partial application work."What happens if someone calls your bound function with new?" The real bind ignores the bound this in that case and uses the freshly constructed object instead. Most interviews don't need it, but knowing it exists is a senior signal:
Function.prototype.myBind = function (context, ...bound) {
const fn = this;
function bound2(...args) {
// When called with `new`, `this` is the new instance — use it.
const ctx = this instanceof bound2 ? this : context;
return fn.apply(ctx, [...bound, ...args]);
}
bound2.prototype = Object.create(fn.prototype || null);
return bound2;
};Don't lead with this version. Write the four-line one first, get it passing, then mention the new case as the thing you'd add if construction matters.
In the editor, write the simple version and confirm both this binding and partial application work. If you have time, layer in the new handling without breaking the first two tests.
Function.prototype.myBind = function (context, ...bound) { // your code here }; // Try it: function greet(greeting, name) { return `${greeting}, ${name}, from ${this.place}`; } const fromIndia = greet.myBind({ place: "India" }, "Hello"); console.log(fromIndia("Asha")); // "Hello, Asha, from India"
Test Code
Enter JavaScript that runs after your solution. It should return a value or a Promise.