基本上,我想要实现以下目标。我有一个函数"ontimeout",它期望一个函数作为参数,并且只有在给定时间(3s)后,条件为true时才调用该函数:
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);
};