Frage

<html>
  <head>
    <title></title>
  <script type="text/javascript">  
    var a = 1;
function b() {
    a = 10;
    return;
    function a() {}
}

</script>
  </head>
  <body>
<script type="text/javascript">
b();
alert(a);
</script>
  </body>
</html>

I am coming from c and java background . Scoping rule is different in java script. I want to know why this program is giving output 1. How this program is working.

War es hilfreich?

Lösung

There is a combination of two things going on here; the scope of variables, and how functions and variables are declared inside a function.

You are declaring a local function inside the b function named a, so that has the same effect as declaring a local variable inside the function that shadows the variable by the same name in the global scope.

It doesn't matter where you create a local variable/function inside a function, it will still be created before the code in the function starts, so doing this:

function b() {
  a = 10;
  return;
  function a() {}
}

is basically the same as:

function b() {
  var a = function(){};
  a = 10;
  return;
}

When the code in the function assigns the value 10 to the variable a, it actually overwrites the local function and replaces it with the number. As function references in Javascript are first class members, they can be passed around like any other value, and also replaced by any other value.

As the code in the function only changes the local variable a the global variable a is unchanged.

Andere Tipps

JavaScript uses function scope. Also, functions are "hoisted" to the top of their scope (the closest function).

function b() {
    a = 10;
    return;
    function a() {}
}

This is being interpreted as:

function b() {
    function a() {}  // function was hoisted
    a = 10;
    return;
}

When a function is declared using function a(){} it's like there was a var there; it's making a local variable. Therefore, the a=10 is the local a, not the global a.

Reference: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting

In javascript scoping unit is a function. In your b function, a is a local function. Therefore, global a variable is unaffected.

About scoping in Javascript language, you can find here: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top