Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

267
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!