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.