9

JavaScript Interview Question: Write Your Own Bind Function | Bits and Pieces

 2 years ago
source link: https://blog.bitsrc.io/common-javascript-interview-question-write-your-own-bind-function-fbdabbbea3da
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Common JavaScript Interview Question: Write Your Own Bind Function

Photo by Michael Held on Unsplash

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK