一旦控制权离开脚本,JavaScript 静态变量是否仍然存在?

发布于 2024-12-07 11:15:15 字数 85 浏览 0 评论 0原文

我有一个关于 JavaScript 中静态变量的问题。它们仅在脚本范围内持续吗?我的意思是,如果控制离开脚本并返回到 html 代码,静态变量是否仍然存在?

I have a question about static variables in JavaScript. Do they only last during the scope of the script? What I mean is what if control leaves the script and goes back to the html code, are the static variables still there?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清泪尽 2024-12-14 11:15:15

我假设你的意思是全局变量而不是静态变量。全局变量在全局文档范围内声明。它们可以从所有方法(函数)访问,并且当您从函数的代码块内修改它们的值时,该值仍然存在,因为您正在修改全局变量。

例如:

<script type="text/javascript">
    global_var = 0; // declared globally
    function global_inc(){
        global_var += 1; // global var incremented by 1
    }

    function local_inc(){
        local_var = global_var; // declared locally, and scope ends at function end.
        local_var += 1; // local var incremented by 1
        alert('global: ' + global_var);
        alert('local: ' + local_var);
    }

    function alert_global(){
        alert('global: ' + global_var);
    }
</script>

<script type="text/javascript">
    alert_global(); // alert global (0)
    global_inc(); // increment global to 1
    local_inc(); // set local to global (1) and increment local to (2), alert both
    alert_global(); // alert global (1)
</script>

您将得到:
来自alert_global() 的“global: 0”警报
local_inc() 中的“global: 1”警报
local_inc() 中的“local: 2”警报
来自alert_global()的“global: 1”警报

I assume that you mean global instead of static variables. Global variables are declared in the global document scope. They are accessible from all methods (functions) and when you modify their value from within a function's code block, the value persists, since you are modifying the global variable.

For example:

<script type="text/javascript">
    global_var = 0; // declared globally
    function global_inc(){
        global_var += 1; // global var incremented by 1
    }

    function local_inc(){
        local_var = global_var; // declared locally, and scope ends at function end.
        local_var += 1; // local var incremented by 1
        alert('global: ' + global_var);
        alert('local: ' + local_var);
    }

    function alert_global(){
        alert('global: ' + global_var);
    }
</script>

<script type="text/javascript">
    alert_global(); // alert global (0)
    global_inc(); // increment global to 1
    local_inc(); // set local to global (1) and increment local to (2), alert both
    alert_global(); // alert global (1)
</script>

You would get:
alert of "global: 0" from alert_global()
alert of "global: 1" from local_inc()
alert of "local: 2" from local_inc()
alert of "global: 1" from alert_global()

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文