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.