简体   繁体   中英

A javascript variable defined outside a function is 'undefined' within the function

Why is MM_SYSTEM_RESTART_SECONDS undefined in the following snippet?

If var MM_SYSTEM_RESTART_SECONDS = 40; is put inside the function, then MM_SYSTEM_RESTART_SECONDS is 40 , but if outside the function, then MM_SYSTEM_RESTART_SECONDS is always 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 )

This just bit me. If you call the function before/above the variable declaration the variable might be undefined.

For example

f("before");

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

f("after");

results in:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM