Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

270
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda