0

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.

Magnar Myrtveit
  • 2,432
  • 3
  • 30
  • 51

2 Answers2

1

Yes, there is! You can use .bind(). Here's an example:

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

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

bar(2);
kognise
  • 612
  • 1
  • 8
  • 23
1

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

bar = (arg) => {
  console.log(this.num + arg);
}
trincot
  • 317,000
  • 35
  • 244
  • 286