0

Consider the following example of a this-bound member in a class.

class Foo {
  foo = "foo";
  bar = () => {
    console.log(this.foo);
  }
}

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

This properly logs foo to the console.

However, trying to achieve the same in the following object literal fails:

const foo = {
  foo: "foo",
  bar() {
    console.log(this.foo);
  }
}

const bar2 = foo.bar;
bar2();

The error is: undefined is not an object (evaluating 'this.foo')

I fully understand why this is happening. So, my question if there is simple way to get the same effect in an object literal.

Playground link

user3612643
  • 5,096
  • 7
  • 34
  • 55
  • You lost the `foo` calling context when you put the function into a standalone variable as a callback. Either use `.bind` to set the proper calling context or define a function which *calls* `foo.bar*. – CertainPerformance Sep 09 '20 at 14:21
  • `foo.bar = foo.bar.bind(foo)`…? Not really any way to do that directly as part of the literal though. – deceze Sep 09 '20 at 14:27
  • bind the context in which you want to execute the bar()...... `bar2.bind(foo)()` will help you – Sheelpriy Sep 09 '20 at 14:31
  • 2
    Don't use `this`. For example `const foo = { foo: "foo", bar: () => console.log(foo.foo) }` – 3limin4t0r Sep 09 '20 at 14:31

0 Answers0