我在javascript中有一个对象。从对象外部调用对象中的方法。我希望这个方法在200ms之后调用自身(一种递归但不完全),直到一个条件满了。
this.setSearchResult = function(data){
if(initiated){
doSetSearchResult(data);
}else{
console.log("Map is not initiated yet. Waiting 200 ms");
setTimeout(function(){setSearchResult(data);}, 200); // <- Error
}
}
以这种方式调用setSearchResult:
mapView = new MapView(imageData);
mapView.setSearchResult(data);
我得到的错误是ReferenceError: setSearchResult is not defined.
克服错误的一种方法是将setTimeout调用更改为:
setTimeout(function(){mapView.setSearchResult(data);}, 200);
但我觉得相当难看(尽管它可能适用于我的应用程序)。
有没有正确的方法呢?我是否必须在setSearchResult中跳过使用setTimeout?
答案 0 :(得分:2)
我认为这应该有效:
this.setSearchResult = function(data){
if(initiated){
doSetSearchResult(data);
}else{
var _this = this;
console.log("Map is not initiated yet. Waiting 200 ms");
setTimeout(function(){_this.setSearchResult(data);}, 200); // <- Error
}
}
这是因为您处于回调函数中,因此您无权访问setSearchResult函数。
答案 1 :(得分:1)
setSearchResult
是MapView对象的一种方法。因此,你必须这样称呼它。在方法本身内部,您可以使用关键字this
来引用方法所属的对象。
如果您在方法中直接使用this.setSearchResult
,则可以使用setTimeout
。但是在window
回调函数中使用它会引用setTimeout
对象,因为window
是this
的方法。要解决此问题,请将// Store this in a variable called self
var self = this;
setTimeout(function() {
// Inside this function "this" points to window, because setTimeout
// is a method of window. Use the previously declared self instead.
self.setSearchResult(data);
}, 200);
存储在另一个变量中,并使用它指向正确的对象。
{{1}}