从javascript中的函数更新全局变量 [英] update global variable from a function in the javascript

查看:63
本文介绍了从javascript中的函数更新全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是情况:

我有一个具有局部变量的函数.我想将该值分配给全局变量,而我们将其分配给另一个函数.

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.

这是代码:

global_var = "abc";

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

function show_global_var_value()
{
    alert(global_var);
}

我在HTML页面中调用show_global_var_value()函数,但显示的是value ="xyz"而不是"abc"

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

我在做什么错了?

推荐答案

除了使用 var 语句声明局部变量外,您需要做的就是 let JS 1.7中引入的语句

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"
}

注意:要在此时(2014年1月)使用JS 1.7,必须在脚本标签中声明该版本:

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>

但是 let 现在已成为ECMAScript Harmony标准的一部分,因此有望在不久的将来完全可用.

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

这篇关于从javascript中的函数更新全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆