Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

Function bind

Function Borrowing

The bind() method allows an object to borrow a method from another object.

The example below creates two objects (person and member), where the member object borrows the fullName method from the person object.

Example

const person = {
  firstName:“John”,
  lastName: “Doe”,
  fullName: function () {
    return this.firstName + ” “ + this.lastName;
  }
}

const member = {
  firstName:“Hege”,
  lastName: “Nilsen”,
}

let fullName = person.fullName.bind(member);

Preserving this

The bind() method is sometimes necessary to prevent losing the correct this context.

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

Example

const person = {
  firstName:“John”,
  lastName: “Doe”,
  display: function () {
    let x = document.getElementById(“demo”);
    x.innerHTML = this.firstName + ” “ + this.lastName;
  }
}

person.display();

When a function is used as a callback, the this context is lost.

In this example, the intention is to display the person’s name after 3 seconds, but it will display undefined instead.

Example

const person = {
  firstName:“John”,
  lastName: “Doe”,
  display: function () {
    let x = document.getElementById(“demo”);
    x.innerHTML = this.firstName + ” “ + this.lastName;
  }
}

setTimeout(person.display3000);

The bind() method resolves this issue.

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

This ensures that the person’s name is displayed after 3 seconds.

Example

const person = {
  firstName:“John”,
  lastName: “Doe”,
  display: function () {
    let x = document.getElementById(“demo”);
    x.innerHTML = this.firstName + ” “ + this.lastName;
  }
}

let display = person.display.bind(person);
setTimeout(display, 3000);

What is this?

In JavaScript, the this keyword refers to an object, but the object it refers to can vary depending on how this is used.

In an object method, this refers to the object that owns the method.

When used alone, this refers to the global object.

In a function, this refers to the global object.

In a function, when in strict mode, this is undefined.

In an event handler, this refers to the element that triggered the event.

Methods like call(), apply(), and bind() allow you to set this to any object.

Note:

this is a keyword, not a variable, and its value cannot be changed.