简体   繁体   中英

update global variable from a function in the javascript

Here is the situation:

I have one function which has local variable. I would like to assign that value to global variable and us it's value in another function.

Here is the code:

global_var = "abc";

function loadpages()
{
    local_var = "xyz";
    global_var= local_var;
}

function show_global_var_value()
{
    alert(global_var);
}

I'm calling show_global_var_value() function in the HTML page but it shows the value = "xyz" not "abc"

What am I doing wrong?

What you need to do apart from declaring local variables with var statement as other pointed out before, is the let statement introduced in JS 1.7

var global_var = "abc";

function loadpages()
{
    var local_var = "xyz";
    let global_var= local_var;
    console.log(global_var); // "xyz"
}

function show_global_var_value()
{
    console.log(global_var); // "abc"
}

Note: to use JS 1.7 at the moment (2014-01) you must declare the version in the script tag:

<script type="application/javascript;version=1.7"></script>

However let is now part of ECMAScript Harmony standard, thus expected to be fully available in the near future.

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