setTimeout 添加条件函数参数

setTimeout add conditional to function parameter

基本上,我想要实现的是以下内容。我有这个函数 'ontimeout',它需要一个函数作为参数,并且只有在给定时间(3 秒)后条件为真时才调用此函数:

EventStreamSource.prototype.ontimeout = function(func){
    setTimeout(function(){
        if(this.source.readyState == 0){
            func()}
    }, 3000);   
};

在另一个脚本中,可能有这样的代码:

source.ontimeout(function(){
    toastr.error('Command stream not established.')
})

然而,这似乎不起作用。我对 javascript 不是很熟悉,我确信我一直在犯一个低级错误,但我也一直在努力解决这个问题太久了,所以如果能有几双额外的眼睛就好了关于这个。

所以实际的问题是如何在新函数中调用 'func'。

提前致谢!

问题是您传递给 setTimeout 的函数会创建自己的 this 上下文,因此 this 不再引用 EventStreamSource 的实例。通过如下闭包传递 this.source

EventStreamSource.prototype.ontimeout = function(func){
    (function(source){ // accept source as an argument to the closure
        setTimeout(function(){
            if(source.readyState == 0){
                func()}
        }, 3000);
    })(this.source); // pass this.source to the closure
};

另一个没有 IIFE(或闭包或任何你想调用它的东西)但解决了同样问题的解决方案:传递给 setTimeout 的函数创建了它自己的 this 作用域,所以首先我们取消引用 this.source 变成一个变量。

EventStreamSource.prototype.ontimeout = function(func){
    var thisSource = this.source;

    setTimeout(function(){
        if(thisSource.readyState == 0){
            func()}
    }, 3000);   
};