Bind In JavaScript Simply Explained

JavaScript

23/08/2021


As the name implies, the bind method binds an object to a function and makes said object accessible in that function through the this keyword.

Take the example below. We define and call a function that is not yet bound to the object user. Consequently, this refers to the global window object instead.

JAVASCRIPT
const user = {
1: 'John Doe'
}
function printUser() { console.log(this) }
printUser() // Window

After we bind user to printUser, we actually print out the user object.

JAVASCRIPT
printUser.bind(user)() // Object { 1: "John Doe" }
const func = printUser.bind(user)
func() // Object { 1: "John Doe" }

2 things to be aware of:

  • The bind method duplicates the original function with the new object bound to it. How you call it is up to you.
  • This will not work on arrow functions!

Adding extra arguments

You may also wish to pass additional arguments to your function while binding. Let's modify our existing function to accept and print a string.

JAVASCRIPT
function printUserAndText(text) { console.log(this, text) }
printUserAndText.bind(user, 'Banana')() // Object { 1: "John Doe" } Banana

It may be confusing at first, but parameters defined in your function must be passed into bind from the second argument onwards.


WRITTEN BY

Code and stuff