Lexical scope/closures in javaScript

前端 未结 4 862
抹茶落季
抹茶落季 2020-12-12 17:28

I understand functions in \'js\' have lexical scope (i.e. functions create their environment (scope) when they are defined not when they are executed.)

funct         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-12 18:27

        function f1() {
              var a = 1;
              f2();
              }
    
        function f2() {
           return a;
        }
        f1(); // a is not defined
    
    1. f2(); does not knows about the a,because you never passed 'a' to it,(That's Scope are created when the functions are defined).Look function f2() would have been able to acess a if it was defined inside f1();[Functions can access the variables in same scope in which they are "DEFINED" and NOT "CALLED"]

      function f() {
         var b = "barb";
         return function(){
                           return b;
                          }
      }
      console.log(b); 
      
    2. First of all You Need to Call f(); after executing f(); it would return another function which needs to be executed. i.e

      var a=f();
      a();
      

      it would result into "barb" ,In this case you are returning a function not the var b;

      function f() {
         var b = "barb";
         return b;
                   };
      
      console.log(f());
      

      This would print barb on screen

提交回复
热议问题