Sign in
Log inSign up

Polyfill for Bind

piyush jaiswal's photo
piyush jaiswal
·Sep 6, 2021·

2 min read

This most common question that one encounters in a javascript interview is polyfills. So today we will look into the most commonly asked question "polyfill for bind".

Before diving into the problem, let us first understand polyfill and bind.

So polyfill is nothing but a fallback for the code written in some different version of javascript so that it becomes compatible with older browsers.

Bind is just adding an object with a function and creating a new function so that the new function can be invoked at a later point in time.

Bind is just adding an object with a function and creating a new function so that the new function can be invoked at a later point in time.

For example :

const obj = {
  firstname: "piyush",
  lastname: "jaiswal"
}
function getDetails(age) {
  console.log({
    firstname: this.firstname,
    lastname: this.lastname,
    age
  });

}

If we try to execute getDetails we will get undefined for firstname and lastname. This is because firstname and lastname are not present in the execution context(this).

So to get the getDetails function working we will make use of the bind function to bind obj with it.

const boundFunction =  getDetails.bind(obj);
console.log(boundFunction(27));

Enough of an introduction about polyfill and bind. Let us see how we can write polyfill for bind.

For writing polyfill we should have a clear understanding of prototype and execution context (this).

Function.prototype.mybind = function(...args) { 
  const context = this; /* execution context ,here it refers to invoking function 
i.e getDetails() */
  const obj = args[0]; // it is the first argument passed to the bind function . i.e obj.
  const rest = args.slice(1); // arguments other than first argument. 
  return function(args) {
    const params = [...rest, args]; /* this is required to handle the case where the user 
 can pass age as a parameter. */
    return context.apply(obj, params); // apply takes the arguments in array format.
  }
}
const newfn = getDetails.mybind(obj);

console.log(newfn(27));

This is all we need to do to write polyfill for bind.