简体   繁体   中英

Local variable in global function

Why does it show "AAA" in the alert instead of "BBB" ?

http://jsfiddle.net/Lp4cS/

var z = "AAA";

function xx() {

    var z = "BBB";
    yy();

}

function yy() {

    alert(z);

}

xx();

var z = "BBB"对于在其中声明的函数(也称为xx是本地的-它显示AAA因为yy可以访问该变量。

This is because you are re-declaring the variable z inside the function

function xx() {

    var z = "BBB";
    yy();

} 

The scope of z is now inside xx()

If you want to update the global var z then u should do as

function xx() {

     z = "BBB";
    yy();

}

http://jsfiddle.net/Lp4cS/1/

Here is an example of how you can get it to work, how you wanted... but this should be avoided... global variables shouldn't be accessed or set. It's considered very bad practice.

window.z = "AAA";

function xx() {

    window.z = "BBB";
    yy();

}

function yy() {

    alert(window.z);

}

xx();

in PHP you can do the same thing...

<?php

$z = "AAA";

function xx() {

    global $z;
    $z = "BBB";
    yy();

}

function yy() {

    global $z;
    echo $z;

}

xx();

This is how it works:

var z = "AAA";    // 1. assign z with "AAA" as global, save it in memory address #1

function xx() {   
  var z = "BBB";  // 3. assign z with "BBB" as local, save it in memory address #2
  yy();           // 4. call function yy()
}

function yy() {   
  alert(z);       // 5. alert z from memory address #1, because i don't know the other z
}

xx();             // 2. call function xx()

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