【问题标题】:Calling subroutine from setInterval callback throws type error [duplicate]从 setInterval 回调调用子例程会引发类型错误 [重复]
【发布时间】:2016-07-13 22:11:43
【问题描述】:

我是 JavaScript/TypeScript 的新手,我想弄清楚这里发生了什么。

class MyClass {

    constructor() {
        this.doThisEverySecond();
        setInterval(this.doThisEverySecond, 1000);  // Tried here
    }

    doThisEverySecond():void {
        console.log("Do some stuff");
        this.subroutineForOrganization();
        console.log("Do more stuff\n");
    }

    subroutineForOrganization():void {
        console.log("Doing many things");
    }
}

const foo:MyClass = new MyClass();
setInterval(foo.doThisEverySecond, 1000);  // And tried here

我想调用一个函数 doThisEverySecond() 并让它每 x 秒执行一次;为了简单的组织目的,我将它的一些功能提取到子例程 subroutineForOrganization() 中。

无论我是在其构造函数中还是在实例化后立即调用 setInterval(),我都会收到以下错误:

Do some stuff
Doing many things
Do more stuff

Do some stuff
D:\Webstorm Projects\Sonification\es5\src_ts\test.js:8
        this.subroutineForOrganization();
             ^

TypeError: this.subroutineForOrganization is not a function
    at Timeout.MyClass.doThisEverySecond [as _repeat] (D:\Webstorm Projects\Sonification\es5\src_ts\test.js:8:14)
    at Timeout.wrapper [as _onTimeout] (timers.js:417:11)
    at tryOnTimeout (timers.js:224:11)
    at Timer.listOnTimeout (timers.js:198:5)

Process finished with exit code 1

我不明白为什么它在第一次从构造函数调用时运行良好,但在使用 setInterval 调用时却出现错误。那时它是一个怎样的功能,但不是现在?是否有某种我不明白的 JavaScript 作用域魔法?

谢谢!

已解决:使用箭头函数调用(如下所述)保留对 this (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Lexical_this) 的引用

【问题讨论】:

  • this 不是你想的那样。
  • 按照上面链接的帖子,这就是最终的工作。我需要做的就是将调用包装在一个匿名函数中。是时候阅读闭包了...setInterval(() => this.doThisEverySecond(), 1000);

标签: javascript node.js typescript


【解决方案1】:

使用Function.prototype.bind函数:

constructor() {
    this.doThisEverySecond();
    setInterval(this.doThisEverySecond.bind(this), 1000);  // Tried here
}

【讨论】:

  • 当我尝试这样做时,我得到:TypeError: Bind must be called on a function
  • 对我来说效果很好。按应有的方式编译和运行。你能在操场上分享你的代码吗?
【解决方案2】:

我相信这是因为您没有正确定义函数。试试这个:

function doThisEverySecond() {
    console.log("Do some stuff");
    this.subroutineForOrganization();
    console.log("Do more stuff\n");
}

还有:

function subroutineForOrganization() {
    console.log("Doing many things");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 2015-12-05
    • 2014-03-27
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多