Javascript Typescript派生类作为回调签名

Javascript Typescript派生类作为回调签名,javascript,typescript,Javascript,Typescript,我试图创建一个基类,该基类发出一个方法来抛出频繁的事件调用,如document.onscroll事件。这是我的基本类: class ThrottledRunner { private timerId: number; lastTimeRun: number; runAtMostEvery = 100; // Here is the Method runThrottled(action: (e: ThrottledRunner) => void) {

我试图创建一个基类,该基类发出一个方法来抛出频繁的事件调用,如
document.onscroll
事件。这是我的基本类:

class ThrottledRunner {
    private timerId: number;
    lastTimeRun: number;
    runAtMostEvery = 100;

    // Here is the Method
    runThrottled(action: (e: ThrottledRunner) => void) {
        var now: number = new Date().getTime();

        if (this.timerId == null) {
            if (now - this.lastTimeRun > (3 * this.runAtMostEvery)) {
                action(this);
                this.lastTimeRun = now;
            }
            this.timerId = setTimeout(function (e: ThrottledRunner) {
                e.timerId = null;
                e.lastTimeRun = new Date().getTime();
                action(e);
            }, this.runAtMostEvery);
        }
    }
}
我的派生类:

class MyTest extends ThrottledRunner {

    myProp: string = "works";

    constructor() {
        super();
        window.addEventListener("scroll", () => this.runThrottled(this.onScroll(this)));
        // Supplied parameters do not match any signature of call target.
        // Could not select overload for 'call' expression.
    }

    onScroll(self: MyTest): void {
        alert(self.myProp);
    }
}

由于MyTest源于throttleRunner,
runThrottled()
应该接受它作为参数,但似乎我错了。我完全改为Typescript+vanillajs,所以请不要回答jQuery。

您看过如何使用下划线JS throttle()函数吗

_.throttle(function, wait, [options])   
创建并返回传递函数的新的限制版本,该版本在重复调用时,每等待毫秒最多只调用一次原始函数。用于限制发生速度快于您所能跟上的事件的速率


下划线有许多非常有用的函数,并具有完整的TypeScript和nuGet支持:

您不能按照执行时立即调用
onScroll
的方式调用它,因为它确实需要等待
runThrottled
应用程序准备就绪。我已将
onScroll
方法更改为不需要参数,因为
上下文设置正确

如果您将班级改为:

class MyTest extends ThrottledRunner {
    myProp: string = "works";
    constructor() {
        super();
        window.addEventListener("scroll",
             () => this.runThrottled(() => this.onScroll()));
    }

    onScroll(): void {
        console.log(this.myProp);
    }
}

将在
运行节流
的上下文中正确

我知道下划线,但不知道键入的版本,谢谢!但是我仍然想知道如何解决参数类型问题。
runthrottled
采用函数/委托样式的参数。您正在将调用
this.OnScroll(this)
的结果传递给函数吗?您可能只需要
this.OnScroll
?@wiredparie我必须将对象传递给OnScroll(),否则
this
将获得
未定义的