Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

161
Vistas
JavaScript .bind mehtod doesn't catch up a context

In sendTo method of user I tried to bind earlier defined function and send this.name as the first argument. But if i try console logging, this.name returns undefind. How to correctcly bind context of user's object to sendTo() mehtod?

function sendFrom(from, to, text) {
    console.log(this);
    return `${from}'s packet --> ${to}  \nmessage: ${text}`;
}

let user = {
    name: "Alex",
    sendTo: sendFrom.bind(this, this.name),
}


user.sendTo = user.sendTo.bind(user);

console.log(user.sendTo("John", "some message"));
{}
undefined's packet --> John  
message: some message
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I guess you can achieve expected behavior by not using any bindings:

function sendFrom(to, text) {
    console.log(this);
    return `${this.name}'s packet --> ${to}  \nmessage: ${text}`;
}

let user = {
    name: "Alex",
    sendTo: sendFrom
}

console.log(user.sendTo("John", "some message"));

But if you want to execute the user's method somewhere else that when binding comes into play:

let alexeSendTo = user.sendTo
alexesSendTo('John', 'Hey John!') // it will loose Alex's user context link

let alexeSendTo = user.sendTo.bind(user)
alexesSendTo('John', 'Hey John!') // now it is marked as Alex message
about 4 years ago · Juan Pablo Isaza Denunciar

0

To undersand why this does not work you have to look at the user object:

sendTo: sendFrom.bind(this, this.name),

This property inside user is what is causing the issue. When this code is run this belongs to the window object and not the user.

So finally sendTo is a method with context as window and first param as window.name

That is why console.log(this) returns the window object.

When you do this: console.log(user.sendTo("John", "some message"));

You are adding the params "John" and "some message" after the already appended param.

So finally params become:

from, to, text -> window.name(undefined in your case), John, some message

Anytime you are using this in this code it is referring to window. There is actually no way to understand binding here and this example is not where you should be using bind

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda