This content originally appeared on Bits and Pieces - Medium and was authored by Aman
What is a Bind method?
The bind method helps us with explicitly binding ‘this’ to the specified object. It basically lets us borrow a function that was meant for one object, to be used for another object.
A bind function will create a function, whose ‘this’ value will be set to the object that is passed into it.
It typically looks like this:
In this example we have an object friend and a function friendInfo. Bind allows us explicitly bind the ‘this’ value to the friend object being passed.
This is why we can use this.name and this.age.
So how can we write our own bind function?
In our example of myBind, we return a function and within that function, we will take our passed in function, explicitly bind it to our passed in context via explicit binding. And since the second parameter in apply is an array, we can also spread other arguments.
Another way to solve this problem would be to create the bind function on the Function prototype.
In the above example, we added a new method on the Function prototype.
In this method, we will only need to explicitly bind the passed in context to the Function prototype itself. And in order to access the prototype, we use ‘this’.
And that’s it! That’s how you can create your own bind method.
Build composable frontend and backend
Don’t build web monoliths. Use Bit to create and compose decoupled software components — in your favorite frameworks like React or Node. Build scalable and modular applications with a powerful and enjoyable dev experience.
Bring your team to Bit Cloud to host and collaborate on components together, and greatly speed up, scale, and standardize development as a team. Start with composable frontends like a Design System or Micro Frontends, or explore the composable backend. Give it a try →
Learn More
- How We Build Micro Frontends
- How we Build a Component Design System
- The Composable Enterprise: A Guide
- 7 Tools for Faster Frontend Development in 2022
JavaScript Interview Question: Write Your Own Bind Function was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Bits and Pieces - Medium and was authored by Aman
Aman | Sciencx (2022-03-13T12:36:17+00:00) JavaScript Interview Question: Write Your Own Bind Function. Retrieved from https://www.scien.cx/2022/03/13/javascript-interview-question-write-your-own-bind-function/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.