Lexical scope/closures in javaScript

前端 未结 4 864
抹茶落季
抹茶落季 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:20

    You get, "ReferenceError: b is not defined" because "b" is not defined where your console.log() call is. There's a "b" inside that function, but not outside. Your assertion that "b is being returned to the global space" is false.

    When you invoke the function returned by your "f()" function, that will return a copy of the value referenced by that closure variable "b". In this case, "b" will always be that string, so the function returns that string. It does not result in the symbol "b" becoming a global variable.

提交回复
热议问题