JavaScript Function bind()

Function Borrowing

By using the bind() method, one object can borrow a method from another object.

The following example creates 2 objects (person and member).

The member object borrows the person object's fullname method:

Instance

const person = {
  firstName: "Bill",
  lastName: "Gates",
  fullName: function () {
    return this.firstName + " " + this.lastName;
  }
}
const member = {
  firstName: "Hege",
  lastName: "Nilsen",
}
let fullName = person.fullName.bind(member);

Try it yourself

retain this

Sometimes the bind() method must be used to prevent loss this.

In the following example, the person object has a display method. In the display method,this refers to the person object:

Instance

const person = {
  firstName: "Bill",
  lastName: "Gates",
  display: function () {
    let x = document.getElementById("demo");
    x.innerHTML = this.firstName + " " + this.lastName;
  }
}
person.display();

Try it yourself

When a function is used as a callback,this will be lost.

This example will try to display the name of the person after 3 seconds, but it will display undefined:

Instance

const person = {
  firstName: "Bill",
  lastName: "Gates",
  display: function () {
    let x = document.getElementById("demo");
    x.innerHTML = this.firstName + " " + this.lastName;
  }
}
setTimeout(person.display, 3000);

Try it yourself

The bind() method solves this problem.

In the following example, the bind() method is used to bind person.display to person.

This example will display the name of the person after 3 seconds:

Instance

const person = {
  firstName: "Bill",
  lastName: "Gates",
  display: function () {
    let x = document.getElementById("demo");
    x.innerHTML = this.firstName + " " + this.lastName;
  }
}
let display = person.display.bind(person);
setTimeout(display, 3000);

Try it yourself

What is this?

in JavaScript,this keyword referencesobject.

referencedwhichthe object depends on the way it is called (used or invoked).

depending on its usage, the keyword this referencing different objects:

  • in an object method,this referencing thisobject.
  • when used alone,this referencedglobal object.
  • in a function,this referencedglobal object.
  • in a function, in strict mode,this is undefined.
  • in the event,this referenced by the event handlerelements.
  • methods such as call(), apply(), and bind() can refer to this referenced byany object.

Note:this is not a variable. It is a keyword. You cannot modify it this .

See also:

Tutorial:JavaScript this