JavaScript Scope and Execution Context

梦想的初衷 提交于 2019-12-01 06:00:54

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!