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

269
Vistas
Nodejs can't access object member within method

I'm setting a variable in the constructor and I can't access it from one of the methods as "this" refers to the function (it shouldn't be the case). Here's what it looks likecode:

class myMiddleware {
    constructor(variable) {
        this.variable = variable;
    }
    middleware(packet, next) {
        console.log(this.variable)
    }
}

I'm using VS 2017 in case that matters.

EDIT: I'm using this as a socket.io socket middleware. Here's how I'm doing so :

 const myInstance = new myMiddleware(myVariable);
 socket.use(myInstance.middleware);
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Explaining the solution posted by robertklep in the comments:

instance.test.bind(instance)

Normally when you call a method like this:

x.method();

the x (whatever it is) is bound to this when the function x.method is called.

If you had a y object and did this:

y.method = x.method;

then when you call:

y.method();

the y would be passed as this, not x.

It also means then when you do:

method = x.method;

and try to call:

method();

the original x will not be bound as this - and this is your problem here. You were passing the method as a function argument losing the original instance object in the process. The function that you passe your method to couldn't know which object you would like to be bound as this.

But all JavaScript functions have method called .bind() that returns a function that calls your method with the right object bound as this.

So this:

let f = x.method.bind(x);

makes an f() function that is more or less equivalent to:

function f(...args) {
  return x.method(...args);
}

or:

let f = (...a) => x.method(...a);

with a difference that you can bind some other object if you want:

let f = x.method.bind(y);

which would work as if x's .method() was called on the y object, even if y doesn't have such a method.

over 4 years ago · Santiago Trujillo 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