In JavaScript, the bind()
method allows you to copy a method from an object. More importantly, you can use the copied method as an independent function but still be able to access the object’s values.
Here’s an example that shows how you can use the bind()
method:
const person = { name: 'John', greet: function() { return `Hello, my name is ${this.name}`; } }; const greet = person.greet; console.log(greet()); // Hello, my name is undefined const boundGreet = greet.bind(person); console.log(boundGreet()); // Hello, my name is John
In this example, the greet
function is a method of the person
object. If you store the person.greet
function into a variable and call it, the function no longer uses the this
value of person
. In other words, it cannot access the name
John. This is why the name
property is undefined
.
But by using the bind()
method, the this
value becomes person
again. This makes the name
property accessible for the copied function greet
.
This is a comprehensive guide to understanding how the bind()
method works in JavaScript.
All the theory is backed up with great examples that support understanding. Besides, you will find answers to some of the most commonly asked questions related to the bind()
method.
Let’s jump into it.
What Is the bind() Method in JavaScript?
The bind()
method in JavaScript creates a new function whose this
value is set to a specific object.
In case you’re not too familiar with the concept of the 'this'
keyword, it’s nothing but a reference to the object itself. It’s like the “me” of a JavaScript object. With this
, the object is capable of accessing its own values and properties.
Every JavaScript object has a keyword this
that refers to the object itself. For instance, if there’s a method inside an object, the method can read the attributes that belong to the object to use them in the method.
Let’s see an example that demonstrates this.
Example 1.
const person = { name: 'John', greet: function() { console.log(`Hello, my name is ${this.name}`); } } person.greet(); // Hello, my name is John
In the last line, person.greet()
makes the person
object call its greet()
method. This prints a greeting by using the person
object’s name
property via this
keyword.
But now, let’s ‘borrow’ the greet()
function from the person
object and store it into a variable.
const person = { name: 'John', greet: function() { console.log(`Hello, my name is ${this.name}`); } } const greet = person.greet; greet(); // Hello, my name is undefined
As you can see, the name
is now undefined
because the function greet
is no longer bound to the person
object. Instead, it’s an independent copy of the person.greet
function. In other words, the this
keyword no longer refers to the person
.
To fix the problem, you can bind the borrowed function to the person
object.
For example:
const person = { name: 'John', greet: function() { console.log(`Hello, my name is ${this.name}`); } } const boundGreet = greet.bind(person); boundGreet(); // Hello, my name is John
You can also use bind()
with object methods in the context of object-oriented programming.
Example 2.
Here are some examples of binding/not binding a class method.
class Person { constructor(name) { this.name = name; } greet() { console.log(`Hello, my name is ${this.name}`); } } const person = new Person('John'); // Example 1. person.greet(); // Hello, my name is John // Example 2. const greet = person.greet; greet() // TypeError: Cannot read property 'name' of undefined // Example 3. const boundGreet = person.greet.bind(person); boundGreet(); // Hello, my name is John
In this code:
- In Example 1 the
person.greet()
works as it just calls thegreet
method on theperson
object. - In Example 2 the
person.greet
is assigned to an independent copygreet
which knows nothing about theperson
object and thus fails to read the name. - In Example 3, the
bind()
method binds thegreet
method to theperson
so that you can successfully use it as an independent function that still has the access to theperson
object.
bind() Method Arguments
The bind()
method takes a minimum of one parameter: the value to be used as the this
keyword when the function is called. This value is referred to as the “binding” of the function.
In addition to the binding, the bind()
method can also take any number of arguments that will be passed to the function as arguments when it is called.
Here is an example of using the bind()
method with both binding and arguments:
const object = { name: 'John', greet: function(greeting, punctuation) { return `${greeting}, my name is ${this.name}${punctuation}`; } }; const greet = object.greet.bind({name: 'Mary'}, 'Hello'); console.log(greet('!')); // Output: "Hello, my name is Mary!"
In this example, the bind()
method is called with two arguments: the {name: 'Mary'}
object as the binding and the string 'Hello'
as the first argument.
When the greet()
function is called with the '!'
argument, it is passed as the second argument to the greet()
function.
Why Use bind() Method?
The bind()
method is useful in JavaScript because it allows you to control the value of this
in a function or method, even if it is executed in a different context.
As you learned, the value of this
depends on how a function or method is called.
- In the global context (i.e., outside of any function), the value of
this
is the global object (in a web browser, this is thewindow
object). - In a function or method that is a property of an object, the value of
this
is the object itself.
There are cases where you may want to specify the value of this
explicitly, regardless of how the function or method is called. This is where bind()
comes in handy.
For example, you may have a function or method that needs to be called in a specific context, but it may be executed in a different context (e.g., as a callback). In this case, you can use bind()
to ensure that the value of this
is set to the desired object, even if the function or method is called in a different context.
bind()
is also useful when working with object-oriented programming in JavaScript. It allows you to bind an object method to the object itself so that the method can be used in a different context without losing its original this
value.
bind() vs call()
In JavaScript, the bind()
and call()
methods allow you to call a function with a specific this
value.
The bind()
method creates a new function that has its this
keyword set to a custom value. The bind()
method does not call the function immediately; it returns a new function that can be called later.
The call()
method is similar to bind()
, but it calls the function immediately, with a given this
value.
Here is an example of using the call()
method:
const object = { name: 'John', greet: function(greeting) { return `${greeting}, my name is ${this.name}`; } }; console.log(object.greet.call({name: 'Mary'}, 'Hello')); // Output: "Hello, my name is Mary"
In summary, the main difference between bind()
and call()
is that bind()
returns a new function, while call()
calls the function immediately.
bind() Arrow Functions
You cannot bind arrow functions in JavaScript.
The key point in arrow functions is that they use the this
value of the parent scope they’re defined in. If you want to bind an arrow function, use a regular function instead.
For example, let’s do an example where we try to bind an arrow function to another object:
const object = { name: 'John', greet: () => { return `Hello, my name is ${this.name}`; } }; const greet = object.greet.bind({name: 'Mary'}); console.log(greet()); // Output: "Hello, my name is undefined"
If you run this code, you see that the name value is undefined
in the greeting. This is because the new this
value was not registered. Instead, the bound function greet
uses the parent scope this
which is undefined
when called outside the object.
Summary
Today you learned how the bind() method works in JavaScript.
To take home, the bind()
method allows you to copy a function from an object and call it independently while being bound to the original object and its values.
Thanks for reading. Happy coding!