开发者

Do JavaScript Static Variables stay present once control leaves the script?

开发者 https://www.devze.com 2023-04-09 18:46 出处:网络
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开发者_如何学Go to the html code

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开发者_如何学Go to the html code, are the static variables still there?


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()

0

精彩评论

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

关注公众号