[英]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:我整理了一个我正在尝试做的简化示例,显然有点做作......我有这个 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();
在其他需要使用它的类中,我会定义
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
:或者,因为有时我只想把它放在一行上(因此
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.如果你想要
this.calc.add(c => c.b = 3)
,那么你需要处理调用 function c => c.b = 3
一旦传递给 add 方法。
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
因此,只需检查该值是 function,如果将其传递
this
function,则在您的 function 中将是c
,然后使用this.b
添加的返回值
Plain old js.普通的旧 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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.