_name
is scoped to any code within the getPerson()
function.
In Javascript, a local variable in a function is scoped to within that particular invocation of the function and each invocation of the function creates a new set of local variables. Also, those local variables are garbage collected just like other variables. They are not strictly stored on a stack that is destroyed when the function exits.
Because of the garbage collection, a variable inside a function will survive as long as code that is still reachable has a reference to that variable. So, in your getPerson()
function, the scope of the _name
variable is a particular invocation of the getPerson()
function, but the lifetime of the variable is as long as some code can still reach that variable, even long after the invocation of getPerson()
has finished.
This is referred to as a closure in Javascript and is an extremely valuable and useful tool.
Because person.getName()
and person.setName()
still have a reference to the _name
variable even long after the getPerson()
function has finished execution, it will remain alive and will not be garbage collected by the language.
So, the scope
is determined by the declaration of the variable. _name
is scoped to within the function that is it declared in and any other child scopes that also exist within that function. Javascript has lexical
scope (which means the scope is determined by where/how it is declared). But, the lifetime of a variable within a scope is separately determined by the garbage collector and a variable within a scope can live much beyond the execution of the function that created the scope as long as some other reachable code still has a reference to that variable.
I like to think of a function scope as, itself, a garbage collected entity in Javascript. While some implementations of Javascript might even be more granular than a whole scope (e.g. garbage collecting individual variables within the scope as possible), the concept of a scope that is garbage collected instead of stack-based gives you a framework for understanding the difference between a language like Javascript and a language like C++ that uses an explicit stack frame to determine the life of a local variable.