简体   繁体   中英

Local and global scope of variables in JavaScript

I have tried reading other posts on the subject but no luck yet. In this code below why doesnt f2() have access to the var defined in f1(). Is not the var "name" a global to the function f2()? Should not f2() see the var "name"?

    function f1() {
     var name = "david";
     function f2() {
        document.writeln(name);
     }
     document.writeln(name);
  }                   

  f2(); // does not write out "david".

your f2() is only defined inside f1() scope. you can't call it globally

Javascript is function level scoped, not block scoped. A function has access to it's parent's function variables but not to variables defined in functions within it. You could return f2 from f1 and call it that way

     function f1() {
         var name = "david";

         document.writeln(name);

         return f2

         function f2() {
            document.writeln(name);
         }

      } 

var f2 = f1();
f2();

You need to read up on Javascript Closures.

Here is a version of your snippet which demonstrates how you can access variables from outer function in an inner function (if you want to call inner function globally).

function f1()
{
   var name = "david";
   return function()
   {
      console.log(name);
   }
}
var f2 = f1();
f2();

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