我知道TypeScript
不是Java
,但我认为这可行。不幸的是,我发现this
里面mainFunction
可能指的是mainFunction
它自己,因为函数是一等公民,对吗?
class MathClass<T> {
total: T;
increment:number = 0;
constructor(value:T) {
this.total = value;
}
mathFunction(num:T) {
this.increment++;
console.log(this.increment + ")" + this.total );
}
}
var list:Array<number> = [1,2,3,4,5,6];
var mathClass = new MathClass<number>(0);
list.forEach(mathClass.mathFunction);
输出:
NaN)undefined
NaN)undefined
NaN)undefined
NaN)undefined
NaN)undefined
NaN)undefined
在Java 8
我可以做到这一点
public class StaticMethodClass<T> implements Consumer<T> {
private T total;
private int increment= 0;
private BiFunction biFunction;
StaticMethodClass(T value,BiFunction<T,T,T> biFunction) {
this.total = value;
this.biFunction = biFunction;
}
public void accept(T t) {
this.increment++;
this.total = (T) this.biFunction.apply( this.total, t );
System.out.println(this.increment + ")" + this.total );
}
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1,2,3,4,5,6 );
list.forEach( new StaticMethodClass<Integer>(6,(a,b) -> a + b) );
}
}
输出
1)1
2)3
3)6
4)10
5)15
6)21
那么可以在Typescript
中实现它吗?