Let's dive into how the function's bind method works to bind the context to any function and understand its internal workings by exploring bind method polyfill.
Ram V
Last Updated Sep 20, 2024
bind method takes the first argument as an object (which works as a context) and the rest arguments are individually passed to the function.
"bind" method returns the borrowed function with bonded context and the returned function can be called
function userInfo(city) {
console.log(`${this.name} is ${this.age} years old, lives in ${city}`);
}
// Object Context
const user = {
name: "Ram",
age: 23,
};
// First Arg - Context (user)
// The rest of the arguments passed to the function, here 'Jaipur' passed to the city arg
const functionWithContext = userInfo.bind(user, 'Jaipur');
functionWithContext(); // Output: Ram is 23 years old, lives in Jaipur
Step1: Validate, that the invoker should function, if not then throw an Error
Step2: Set context to globalThis, if nothing is defined. globalThis has window context in the browser and global in the Node environment. It means if there is no context defined as part bind(), then the default context is the window.
Step3: Create a symbol and assign the function to that symbol key, it works like below
let's say context (object) has a key mapped to the function, and in this case, that function can access the object context
context obj {
context keys
<unique symbol key> : this 👈 Now this has access to the whole context object
}
Step4: Finally Return a function, and on call of that bonded function it calls currentContext[<unique symbol key>] with provided rest of the arguments as part of bind and while calling that function.
Function.prototype.myCustomBind = function (context, ...args) {
// Check if the myCustomBind is invoked by a function <this>.myCustomBind()
if (typeof this !== "function") {
throw new Error(this + "is not a function");
}
// Set the context to the provided context or globalThis if none is provided
const currentContex = context || globalThis;
// Create a unique property to avoid name collisions
const newFunc = Symbol();
// Assign the original function to the new property in the context
currentContex[newFunc] = this;
// Return a new function that, when called, will execute the original function
return function (...newArgs) {
// Call the original function with the original args and any new args
return currentContex[newFunc](...args, ...newArgs);
};
};
const defaultBind = userType.bind(user);
defaultBind(); // Ram is 23 years old
const bindFunc = userType.myCustomBind(user);
bindFunc(); // Ram is 23 years old
Once you understand how binds work, it will be very easy to understand the other function methods call & apply and their polyfill implementation.
Anuj Sharma
Last Updated Aug 29, 2024
Understand important web authorization techniques to enhance role-based authentication for any web application with popular techniques like Session & JSON Web Token (JWT)
Anuj Sharma
Last Updated Nov 16, 2024
A brief explanation of Cross-Origin Resource Sharing (CORS) concept to enable client application accessing resources from cross domain and HTTP headers involved to enable resource access.
Vivek Chavan
Last Updated Sep 15, 2024
You will get a clear understanding about working with any rest api and common concepts asked during interviews
Anuj Sharma
Last Updated Aug 29, 2024
Easy to understand 5 rules, that cover the behaviour of the "this" keyword in different contexts and helps you to master this keyword for any javascript interview.
Anuj Sharma
Last Updated Sep 3, 2024
Most comprehensive frontend system design cheat sheet to help in approaching the system design interview in the best-structured way. Covered 7 most important frontend system design interview topics.
Anuj Sharma
Last Updated Aug 31, 2024
Understanding promise's methods is important to call APIs in parallel and it's an important concept to know for any machine coding interview.
© 2024 FrontendGeek. All rights reserved