0

What's the difference between a variable:

const a = console.log;
a('HELLO');

and an arrow function:

const a = (str) => console.log(str);
a('HELLO');

And why in case of using a class member it doesn't work

class MyClass {
    foo;
    str;

    constructor(str, foo) {
        this.str = str;
        this.foo = foo;
    }

    getFoo() {
        return this.foo(this.str);
    }
}

const instance = new MyClass(123, console.log);

// works
const f = (str) => {
    instance.getFoo(str);
}

f('Hello');

// doesn't works -> this.str is undefined
const f = instance.getFoo;

f('Hello');
j08691
  • 204,283
  • 31
  • 260
  • 272
Petr Schukin
  • 170
  • 2
  • 12

1 Answers1

1

variable = classInstance.function actually just returns a reference to the function in the prototype, not linked to the actual instance, the this.* looks for global variables.

If you want to be able to have another variable store the function with the context of that variable, you need to use .bind(...) or similar

You can also give it a custom context

class MyClass {
    foo;
    str;

    constructor(str, foo) {
        this.str = str;
        this.foo = foo;
    }

    getFoo() {
        return this.foo(this.str);
    }
}

const instance = new MyClass(123, console.log);

// give it the context object
const f = instance.getFoo.bind(instance);

f('Hello');

const f2 = instance.getFoo.bind({ str: "abcd", foo: console.log});

f2("...");

// Equal to the prototype
console.log(instance.getFoo == MyClass.prototype.getFoo);
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34