开发者

update global variable from a function in the javascript

Here is the situation:

I have one function which has local variable. I would li开发者_开发百科ke 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜