setTimeout和“this”在JavaScript中 [英] setTimeout and "this" in JavaScript
问题描述
我有一个方法使用 setTimeOut
属性,并调用另一个方法。在初始加载方法2工作正常。但是,超时后,我得到一个错误,说 method2
是未定义的。我在这里做错了什么?
例如:
prototype.method = function()
{
// method2根据传递的id返回图片
this.method2('useSomeElement')。src =http://www.some。 url;
timeDelay = window.setTimeout(this.method,5000);
};
test.prototype.method2 = function(name){
for(var i = 0; i if images [i] .id.indexOf(name)> 1){
return document.images [i];
}
}
};
问题是setTimeout全局范围。基本上,你正在调用method()类,但不是从this。相反,你只是告诉setTimeout使用函数method,没有特定的范围。
要解决这个问题,您可以将函数调用包装到另一个引用正确变量的函数调用中。它将看起来像这样:
test.protoype.method = function()
{
var that = this;
// method2根据传递的id返回图片
this.method2('useSomeElement')。src =http://www.some.url;
var callMethod = function()
{
that.method();
}
timeDelay = window.setTimeout(callMethod,5000);
};
可以是this,因为callMethod()在方法范围内。
当您需要将参数传递给setTimeout方法时,此问题变得更加复杂,因为IE不支持超过两个参数setTimeout。在这种情况下,您需要阅读关闭。
此外,由于方法()总是调用method(),所以你将自己设置为一个无限循环。
I have a method that uses setTimeOut
property and makes a call to another method. On initial load method 2 works fine. However, after timeout, I get an error that says method2
is undefined. What am I doing wrong here?
ex:
test.prototype.method = function()
{
//method2 returns image based on the id passed
this.method2('useSomeElement').src = "http://www.some.url";
timeDelay = window.setTimeout(this.method, 5000);
};
test.prototype.method2 = function(name) {
for (var i = 0; i < document.images.length; i++) {
if (document.images[i].id.indexOf(name) > 1) {
return document.images[i];
}
}
};
The issue is that setTimeout() causes javascript to use the global scope. Essentially, you're calling the method() class, but not from "this". Instead you're just telling setTimeout to use the function "method", with no particular scope.
To fix this you can wrap the function call in another function call that references the correct variables. It will look something like this:
test.protoype.method = function()
{
var that = this;
//method2 returns image based on the id passed
this.method2('useSomeElement').src = "http://www.some.url";
var callMethod = function()
{
that.method();
}
timeDelay = window.setTimeout(callMethod, 5000);
};
"that" can be "this" because callMethod() is within method's scope.
This problem becomes more complex when you need to pass parameters to the setTimeout method, as IE doesn't support more than two parameters to setTimeout. In that case you'll need to read up on closures.
Also, as a sidenote, you're setting yourself up for an infinite loop, since method() always calls method().
这篇关于setTimeout和“this”在JavaScript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!