• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

135
Vistas
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');
almost 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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

almost 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda