JavaScript Scope and Execution Context

前端 未结 2 1907
感情败类
感情败类 2021-01-05 19:25

I am trying to understand JavaScript scope rules. What I have read in textbooks and the documentation is confusing.

It seems to me that JavaScript is a statically (o

相关标签:
2条回答
  • 2021-01-05 19:56

    It always comes down to lexical scoping which is function are executed with its scope chain when it is defined, not when it is invoked.

    The anonymous function is defined in the local scope of function changeColor instead of the global scope. Hence when it is executed again, it prints out the color green which is listed in the local scope of function changeColor.

    0 讨论(0)
  • 2021-01-05 20:23

    This is indeed a major difference between C/C++ and JavaScript: JavaScript is a reference-counted, garbage-collected language, which means that objects can be reclaimed by the engine when they no longer have any references to them. The function you assign to printColor isn't on the stack, per se, as it would be in C or C++; it's allocated dynamically and then assigned to a variable outside your current scope. So, when control flow returns from changeColor, the anonymous function still has a reference count of 1 since the outer printColor refers to it, and thus it's usable from the outer scope.

    So, your example isn't so much of a scoping issue--it's clear that you declare printColor outside of the function scope of changeColor. When you define changeColor, it closes the upvalue printColor into the new function scope, making it accessible. Like Combat said, if you add a var to the second, inner definition of printColor, it'll shadow the first printColor you declared and it won't be accessible outside that function block.

    As far as other issues to be aware of, yes, there are quite a few, but see my comment on your original post for a good start.

    0 讨论(0)
提交回复
热议问题