DEV Community

Andrés Valdivia Cuzcano
Andrés Valdivia Cuzcano

Posted on

8 2

Entendiendo el método bind()

El método bind() se usa para crear una nueva función donde el primer parámetro es el objeto al cual se quiere hacer referencia cuando se usa la keyword this dentro de la función.

Por ejemplo, se tiene los siguiente dos objetos:

const person1 = {
    name: 'Harvey',
    age: 30,
    getData(hobby) {
        return `Hello, I'm ${this.name}, I'm ${this.age} and I like to ${hobby}`
    }
}

const person2 {
    name: 'Spencer',
    age: 24
}
Enter fullscreen mode Exit fullscreen mode

Como podemos ver, el objeto student no tiene el método getData(), sin embargo, podemos hacer uso de este gracias al método bind ya que podemos pasarle como primer parámetro al objeto student, por lo que this apuntará a este objeto.

const person = {
    name: 'Harvey',
    age: 30,
    getData: function(hobby) {
        return `Hello, I'm ${this.name}, I'm ${this.age} and I like to ${hobby}`
    }
}

const student = {
    name: 'Spencer',
    age: 22
}

const getStudentData = person.getData.bind(student);

console.log(getStudentData('play videogames')); // Hello, I'm Spencer, I'm 22 and I like to play videogames
Enter fullscreen mode Exit fullscreen mode

Otra forma de pasarle los parámetros necesarios a la función es usando el mismo método bind(), ya que, si bien el primer parámetro hace referencia al objeto que usaremos, a partir del segundo parámetro serán los argumentos definidos en la función original.


const getStudentData = person.getData.bind(student, 'play videogames');

console.log(getStudentData()); // Hello, I'm Spencer, I'm 22 and I like to play videogames
Enter fullscreen mode Exit fullscreen mode

💡 Cuando se vea la expresión this.cualquierMetodo.bind(this) es porque se esta llamando el método de dicho objeto y para evitar perder la referencia del mismo se establece de forma explícita mediante el método bind().

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay