它可能非常容易,但我无法解决发生了什么。Javascript:无法真正理解函数返回
function doSomething(a)
{
var num=10;
return setTimeout(
function(){ a(num); }, 1000);
}
,实际上混淆我是一个(NUM)部分的唯一的事。它究竟做了什么?
提醒:我真的在问,因为我不熟悉javascript语法。
它可能非常容易,但我无法解决发生了什么。Javascript:无法真正理解函数返回
function doSomething(a)
{
var num=10;
return setTimeout(
function(){ a(num); }, 1000);
}
,实际上混淆我是一个(NUM)部分的唯一的事。它究竟做了什么?
提醒:我真的在问,因为我不熟悉javascript语法。
当function
doSomething()
执行它被传递的参数a
, a
也是一些function
当setTimeout()
期满之后1秒, 然后调用function
a()
通过称为num
Example usage的论点,然后调用:
// call doSomething() passing the test() function as an argument
doSomething(test);
// takes a number as an argument and shows an alert with that value
function test(number)
{
alert(number);
}
// takes a function as an argument that will perform a 1 second timeout then execute the function called a
function doSomething(a)
{
var num=10;
return setTimeout(
function(){ a(num); }, 1000);
}
它使用变量num
引用的值作为参数,调用变量a
所引用的函数。
s etTimeout返回timeoutID可用于使用clearTimeout取消它,因此,如果您运行DoSomething的了很多次,你会得到不同的整数代表不同timeoutID。
在你的情况一个必须是一个函数,所以你可以使用参数NUM称之为
例子:
function doSomethingElse (justANumber) {
return justANumber + 1;
}
// Here you call your function
doSomething(doSomethingElse);
// or another special case
doSomething(function (justANumber) {return justANumber + 1;});
但在这里,一个是对doSomething的输入。那么它如何作为一个功能? – Ali 2012-04-14 19:41:30
@rolandbishop JavaScript的功能是一流的。 http://en.wikipedia.org/wiki/First-class_function – 2012-04-14 19:42:00
@rolandbishop:函数就像所有其他的值一样,所以它们可以在变量中传递。 – 2012-04-14 19:42:33