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

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

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 Relatório

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