2012-04-14 56 views
0

它可能非常容易,但我无法解决发生了什么。Javascript:无法真正理解函数返回


function doSomething(a) 
{ 
    var num=10; 
    return setTimeout(
    function(){ a(num); }, 1000); 
} 

,实际上混淆我是一个(NUM)部分的唯一的事。它究竟做了什么?
提醒:我真的在问,因为我不熟悉javascript语法。

回答

3

functiondoSomething()执行它被传递的参数aa也是一些functionsetTimeout()期满之后1秒, 然后调用functiona()通过称为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); 
} 
0

它使用变量num引用的值作为参数,调用变量a所引用的函数。

+0

但在这里,一个是对doSomething的输入。那么它如何作为一个功能? – Ali 2012-04-14 19:41:30

+0

@rolandbishop JavaScript的功能是一流的。 http://en.wikipedia.org/wiki/First-class_function – 2012-04-14 19:42:00

+3

@rolandbishop:函数就像所有其他的值一样,所以它们可以在变量中传递。 – 2012-04-14 19:42:33

0

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;});