Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

187
Views
Difference between variable and an arrow function

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');
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!