Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

120
Vistas
Use Arrow Function in Class Method to access Class Property

I've put together a simplified example of what I'm trying to do, obviously a bit contrived... I have this class:

export class myClass {

    a = 'bar';
    b = 0;

    save(x: any = null): void {
        //save all properties
        //...
    }
}

In other classes that need to use it, I will define foo = new myClass();

Then it can be used either as:

this.foo.b = 3
this.foo.save();

or, because sometimes I just want it on one line (hence the x: any = null:

this.foo.save(this.foo.b = 3);

I would like to write the single line version more elegantly, and feel something like this should be possible... is it?

//How can I make this possible?
this.foo.save(c => c.b = 3)

if it is possible, what would the add method look like?

Many thanks!

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Answer for the original question.

If you want this.calc.add(c => c.b = 3), then you need to handle invoking the function c => c.b = 3 once passed to the add method.

So just check the value is a function, if it is then pass this to the function, which would be c in your function, then the return value you add with this.b

Plain old js.

class Calculator {
  constructor() {
    this.a = 10
    this.b = 0
    this.sum = 0
  }
  add(x) {
    this.sum = this.a + (typeof x === 'function' ? x(this) : x)
  }
}

const calc = new Calculator()

calc.add(c => c.b = 3)
console.log(calc.sum)

calc.add(1)
console.log(calc.sum)

about 4 years ago · Juan Pablo Isaza Denunciar

0

Implicitly assigning is anti pattern

// Something that you should avoid
this.calc.b = 3
class Calc {
    constructor(private a: number = 0, private b: number = 0) {}

    setA(a: number) {
        this.a = a;
        return this;
    }

    setB(b: number) {
        this.b = b;
        return this;
    }

    sum() {
        return this.a + this.b;
    }
}

const calc = new Calc();

// will return 0
console.log(calc.sum()); 

// will return 6
console.log(calc.setA(1).setB(5).sum());


const calc1 = new Calc(1,2);

// will return 3
console.log(calc1.sum());
about 4 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 Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda