Search code examples
javascriptfunctionmethodsthismethod-call

Call method stored in variable without specifying this


Consider the following code.

class Foo {
  num = 0;
  bar = function(arg) {
    console.log(this.num + arg);
  }
}

const foo = new Foo();
const bar = foo.bar;

foo.bar(1);

bar(2);

bar.call(foo, 3);

foo.bar(1); logs 1.

bar(2); throws Uncaught TypeError: Cannot read property 'num' of undefined.

bar.call(foo, 3); logs 3.

Is there a way to store the function foo.bar in a variable in such a way that it can be called without specifying the this object?

I know that the following would work.

const foobar = function(arg) {
  foo.bar(arg);
}

Is there a way to avoid creating the intermediary function? I want to pass methods as arguments to another function, and having to create lots of intermediary functions would really reduce code readability.


Solution

  • Define the field with an arrow function; that will let this refer to the instance:

    bar = (arg) => {
      console.log(this.num + arg);
    }