简体   繁体   中英

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!

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM