TypeScript与Java对象属性

时间:2014-09-26 16:01:45

标签: functional-programming typescript java-8

我知道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中实现它吗?

0 个答案:

没有答案