繁体   English   中英

使用 Class 方法中的箭头 Function 访问 Class 属性

[英]Use Arrow Function in Class Method to access Class Property

我整理了一个我正在尝试做的简化示例,显然有点做作......我有这个 class:

export class myClass {

    a = 'bar';
    b = 0;

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

在其他需要使用它的类中,我会定义foo = new myClass();

然后它可以用作:

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

或者,因为有时我只想把它放在一行上(因此x: any = null

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

我想把单行版写的更优雅一些,感觉这样的事情应该是可以的。。。是吗?

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

如果可能的话,添加方法会是什么样子?

非常感谢!

回答原始问题

如果你想要this.calc.add(c => c.b = 3) ,那么你需要处理调用 function c => c.b = 3一旦传递给 add 方法。

因此,只需检查该值是 function,如果将其传递this function,则在您的 function 中将是c ,然后使用this.b添加的返回值

普通的旧 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)

隐式赋值是反模式的

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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