polyfill for Function.bind
This blog is a part of series where I'll be writing polyfills for different inbuilt Javascript methods.
Polyfill is a piece of code (usually written in Javascript) used to provide modern functionality to older browsers which do not support it natively. It acts as a browser fallback.
Function.prototype.bind()
Javascript provides an inbuilt method to be used with functions called bind
which takes a this
value as it's argument and returns the function with the provided this
value.
For Example:
const shivObj = {
name: "Shivaansh Agarwal",
work: "Frontend Developer"
};
function printUserInfo(city){
console.log(`Hey I'm ${this.name} working as a ${this.work} from ${city}.`);
}
const getMyDetails = printUserInfo.bind(shivObj, "Bangalore");
getMyDetails();
// Hey I'm Shivaansh Agarwal working as a Frontend Developer from Bangalore.
Polyfill for Function.prototype.bind()
Firstly, let's understand what the actual bind method takes as an input. So from MDN documentation for bind method we came to know that, bind
method takes the following arguments as input.
- thisArg: The value to be passed as the
this
parameter to the targetfunction
when the bound function is called. - arg1, arg2, ... argN (Optional): The arguments to be passed to the actual function.
Secondly, what is the bind supposed to return?
It's supposed to return a copy of the given function, with the specified this
value, and the arguments (if passed).
Now this how I would my implement a basic version of Function.prototype.bind()
Let's name this myBind()
Function.prototype.myBind = function(thisArg, ...args){
const functionRef = this;
return function(...params){
functionRef.apply(thisArg, [...args, ...params])
}
}
const shivObj = {
name: "Shivaansh Agarwal",
work: "Frontend Developer"
};
function printUserInfo(city){
console.log(`Hey I'm ${this.name} working as a ${this.work} from ${city}.`);
}
const getMyDetails = printUserInfo.myBind(shivObj, "Bangalore");
getMyDetails();
// Hey I'm Shivaansh Agarwal working as a Frontend Developer from Bangalore.
We can obviously add more error handling scenarios to make this method more robust and practically useful, but from an interview's point this might be sufficient usually.