Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

188
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda