javascript 函数内部的 setTimeout 调用函数 - Scope-Issue
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8187038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
setTimeout calling function inside function - Scope-Issue
提问by Julian
So, the problem is that I have a function inside a function that needs to be called by setTimeout. That doesn't work however because setTimeout will assume that the function it calls has the root as its' scope.
所以,问题是我在需要由 setTimeout 调用的函数中有一个函数。但是,这不起作用,因为 setTimeout 将假定它调用的函数具有根作为其作用域。
Any idea how I could solve this without changing the scope of the function?
知道如何在不改变函数范围的情况下解决这个问题吗?
Edit:
编辑:
Here is what I mean:
这就是我的意思:
function general(){
function saysomething(){
console.log('hi there');
}
setTimeout("saysomething();", 1000);
}
The setTimeout fails..
setTimeout 失败..
回答by Ben
function general(){
function saysomething(){
console.log('hi there');
}
setTimeout(saysomething, 1000);
}
回答by Johnny Craig
Not positive this is what you mean but you can pass the variables when you call the function in the setTimeout
不是肯定的,这就是您的意思,但是您可以在 setTimeout 中调用函数时传递变量
function f1(){
var a='1';
var b='b';
setTimeout(function(){f2(a,b);},1000)
}
function f2(a,b){
alert(a + b);
}
f1();