Typescript 使用TaskTimer每n秒调用一个函数

Typescript 使用TaskTimer每n秒调用一个函数,typescript,timer,Typescript,Timer,我有一个关于在Typescript中使用类的问题: 如果我在没有类的情况下运行此代码 var timer = new TaskTimer(1000); function getData() { return Date.now(); } function print1() { console.log(getData()); } timer.add({ id: 'job1', tickInterval: 2, totalRuns: 0, call

我有一个关于在Typescript中使用类的问题:

如果我在没有类的情况下运行此代码

var timer = new TaskTimer(1000);

function getData() {
    return Date.now();
}

function print1() {
    console.log(getData());
}

timer.add({
    id: 'job1',
    tickInterval: 2,
    totalRuns: 0,
    callback() {
        print1();
    }
});

// Start the timer
timer.start();
它工作得很好!但是如果我尝试运行相同的代码,只使用类,它会抛出错误:

error TS2339: Property 'print1' does not exist on type 'TaskCallback | ITaskOptions | Task | (TaskCallback | ITaskOptions | Task)[]'.
Property 'print1' does not exist on type 'TaskCallback'.
代码如下:

class App {

    timer: TaskTimer;

    constructor() {
        this.timer = new TaskTimer(1000);
    }

    getData() {
        return Date.now();
    }

    print1() {
        console.log(this.getData);
    }

    print2() {
        this.timer.add({
            id: 'job1',
            tickInterval: 1,
            totalRuns: 0,
            callback() {
                this.print1();
            }
        });

        this.timer.start();
    }
}

let app = new App();
app.print2();

在第二种情况下,我做错了什么?我可能很想弄明白,但现在我就是不明白…

使用定义回调使其成为:

换句话说,从回调内部看,这不一定是类实例,而是调用上下文的内容

如果将回调定义为绑定函数,则该函数将保留为类实例:

            callback: () => {
                this.print1();
            }
            // Or shorthand:
            callback: () => this.print1()


TaskTimer从何而来?从这里:我使用了“TaskTimer”中的import{TaskTimer};在这两个示例中,我怀疑回调中的this没有引用实例。你能试一下const self=this,然后在cb中使用self吗?@k0pernikus按照你说的那样试过,我已经排除了错误,但现在它正在打印[Function:getData],而不是当前的时间戳…@k0pernikus,如果我使用的是console.logself.getData;在回调中,而不是在self.print1中;它打印正确,所以。。。我猜现在是print1函数的问题了?
            callback: () => {
                this.print1();
            }
            // Or shorthand:
            callback: () => this.print1()