我有一些JavaScript代码,看起来像:
function statechangedPostQuestion()
{
//alert("statechangedPostQuestion");
if (xmlhttp.readyState==4)
{
var topicId = xmlhttp.responseText;
setTimeout("postinsql(topicId)",4000);
}
}
function postinsql(topicId)
{
//alert(topicId);
}
我得到一个错误,topicId没有定义
在我使用setTimeout()函数之前,一切都在工作。
我希望我的postinsql(topicId)函数在一段时间后被调用。
我该怎么办?
由于IE中的第三个可选参数有问题,并且使用闭包阻止我们改变变量(例如在循环中),但仍然达到预期的结果,我建议以下解决方案。
我们可以尝试像这样使用递归:
var i = 0;
var hellos = ["Hello World1!", "Hello World2!", "Hello World3!", "Hello World4!", "Hello World5!"];
if(hellos.length > 0) timeout();
function timeout() {
document.write('<p>' + hellos[i] + '<p>');
i++;
if (i < hellos.length)
setTimeout(timeout, 500);
}
我们需要确保没有其他东西改变这些变量,并且我们写了一个适当的递归条件来避免无限递归。
取代
setTimeout("postinsql(topicId)", 4000);
with
setTimeout("postinsql(" + topicId + ")", 4000);
或者更好的是,用匿名函数替换字符串表达式
setTimeout(function () { postinsql(topicId); }, 4000);
编辑:
Brownstone的评论是不正确的,这将按照预期工作,正如在Firebug控制台中运行它所演示的那样
(function() {
function postinsql(id) {
console.log(id);
}
var topicId = 3
window.setTimeout("postinsql(" + topicId + ")",4000); // outputs 3 after 4 seconds
})();
请注意,我同意其他人的观点,即您应该避免将字符串传递给setTimeout,因为这将在字符串上调用eval(),而不是传递一个函数。
//这是三个非常简单明了的答案:
function fun() {
console.log(this.prop1, this.prop2, this.prop3);
}
let obj = { prop1: 'one', prop2: 'two', prop3: 'three' };
let bound = fun.bind(obj);
setTimeout(bound, 3000);
// or
function funOut(par1, par2, par3) {
return function() {
console.log(par1, par2, par3);
}
};
setTimeout(funOut('one', 'two', 'three'), 5000);
// or
let funny = function(a, b, c) { console.log(a, b, c); };
setTimeout(funny, 2000, 'hello', 'worldly', 'people');
//这是三个非常简单明了的答案:
function fun() {
console.log(this.prop1, this.prop2, this.prop3);
}
let obj = { prop1: 'one', prop2: 'two', prop3: 'three' };
let bound = fun.bind(obj);
setTimeout(bound, 3000);
// or
function funOut(par1, par2, par3) {
return function() {
console.log(par1, par2, par3);
}
};
setTimeout(funOut('one', 'two', 'three'), 5000);
// or
let funny = function(a, b, c) { console.log(a, b, c); };
setTimeout(funny, 2000, 'hello', 'worldly', 'people');
Hobblin已经就这个问题发表了评论,但它确实应该是一个答案!
使用Function.prototype.bind()是最干净和最灵活的方法(能够设置this上下文的额外奖励):
setTimeout(postinsql.bind(null, topicId), 4000);
欲了解更多信息,请参阅这些MDN链接:
https://developer.mozilla.org/en/docs/DOM/window.setTimeout#highlighter_547041
https://developer.mozilla.org/en/docs/JavaScript/Reference/Global_Objects/Function/bind#With_setTimeout