Función JavaScript método bind()


Tabla de contenido

    Mostrar tabla de contenidos


Préstamo de funciones

Con el método bind(), un objeto puede tomar prestado un método de otro objeto.

El siguiente ejemplo crea 2 objetos (persona y miembro).

El objeto miembro toma prestado el método de nombre completo del objeto persona:

Ejemplo

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);

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Function bind()</h1>

<p>This example creates 2 objects (person and member).</p>
<p>The member object borrows the fullname method from person:</p> 

<p id="demo"></p>

<script>
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);

document.getElementById("demo").innerHTML = fullName();
</script>

</body>
</html>

Preservando esto

A veces se debe utilizar el método bind() para evitar perder esto.

En el siguiente ejemplo, el objeto persona tiene un método de visualización. En el método de visualización, this se refiere al objeto persona:

Ejemplo

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

person.display();

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Function bind()</h1>

<p>In this example, the person object has a display method:</p>

<p id="demo"></p>

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

person.display();
</script>

</body>
</html>

Cuando se utiliza una función como devolución de llamada, esto se pierde.

Este ejemplo intentará mostrar el nombre de la persona después de 3 segundos, pero en su lugar mostrará undefinido:

Ejemplo

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

setTimeout(person.display, 3000);

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Function bind()</h1>

<p>This example will try to display a person name after 3 seconds.</p>

<p id="demo"></p>

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

setTimeout(person.display, 3000);
</script>

</body>
</html>

El método bind() resuelve este problema.

En el siguiente ejemplo, el método bind() se utiliza para vincular person.display a person.

Este ejemplo mostrará el nombre de la persona después de 3 segundos:

Ejemplo

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);

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Function bind()</h1>

<p>This example will display a person name after 3 seconds:</p>

<p id="demo"></p>

<script>
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);
</script>

</body>
</html>


¿Qué es esto?

En JavaScript, la palabra clave this se refiere a un objeto.

Qué objeto depende de cómo se invoca (usa o llama) este.

La palabra clave this se refiere a diferentes objetos dependiendo de cómo se use:

  • En un método de objeto, este se refiere al objeto.

  • Por sí solo, este se refiere al objeto global.

  • En una función, this se refiere al objeto global.

  • En una función, en modo estricto, este es indefinido.

  • En un evento, este se refiere al elemento que recibió el evento.

  • Métodos como call(), apply() y bind() puede referir este a cualquier objeto.

Nota

este no es una variable. Es una palabra clave. No puede cambiar el valor de this.

Ver también:

El tutorial de JavaScript este