2

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);
aslad
  • 120
  • 11

1 Answers1

3

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.

rsp
  • 107,747
  • 29
  • 201
  • 177