在函数外部定义的javascript变量在函数内是“未定义的”

时间:2012-03-07 00:10:17

标签: javascript

为什么MM_SYSTEM_RESTART_SECONDS undefined位于以下代码段中?

如果将var MM_SYSTEM_RESTART_SECONDS = 40;放入函数内,则MM_SYSTEM_RESTART_SECONDS40,但如果在函数外部, 然后MM_SYSTEM_RESTART_SECONDS始终是undefined

var MM_SYSTEM_RESTART_SECONDS = 40;


function wait_until_MM_restarts()
{
    restart_timeout_start_seconds = get_cookie( "restart_timeout_start_seconds" )
    elapsed_restart_seconds =  elapsed_seconds( restart_timeout_start_seconds )
    append_debug_message( elapsed_restart_seconds + "/" +   MM_SYSTEM_RESTART_SECONDS )
    if( elapsed_restart_seconds > MM_SYSTEM_RESTART_SECONDS )

1 个答案:

答案 0 :(得分:2)

这只是我的意思。如果在变量声明之前/之上调用函数,则变量可能未定义。

例如

f("before");

var value = 99;
function f(msg)
{    
  alert("msg=" + msg + " value=" + value);
}

f("after");

结果:

msg=before value=undefined
msg=after value=99

http://jsfiddle.net/qUhQV/4/