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

118
Views
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 answers
Answer question

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 Report

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