Search code examples
javascriptclosuresprivate-members

javascript and private variables


I'm looking into private variables in JavaScript and I understand the syntax for them, but I'm curious as to how they're working more under the hood with the functions.

It seems functions declared inside another function, even after being saved as the object value of an external variable, are either

  1. linked to outer function's scope and have access to its variables, OR
  2. the value of the variable in the outer function is simply passed to the inner function(closure).

Which one is it or is it something different I haven't thought of. thanks

 function Cat(name,amt){
    this.name=name;
    let num=amt;//private
    let num2=5;//private
    this.add=function(){//is privileged and has access to variables during object creation and is public
        return num+num2;
    }
}
Cat.prototype.scratch=function(){
    let amt= this.add();
    console.log(this.name + " scratched " + amt + " times." );
}

let spots= new Cat("spots", 5);

Spots.scratch()// prints "spots scratched 10 times."

Solution

  • The names and values of variables within a function are held in an environment record created when a function gets executed and held in its Lexical Environment.

    From section 8.1 of the ECMA Standard Version 7 specification:

    A Lexical Environment consists of an Environment Record and a possibly null reference to an outer Lexical Environment.

    So in effect the inner function has a record of its own variables and their values, and a pointer to the outer function's record of its variables and values and so on until there are no more outer functions and global scope has been reached.

    Although LexicalEnvironment is a descriptive abstraction of how ECMA script works, in real terms this means if you save a reference to an inner function outside its scope chain, variables it uses anywhere within its private, non-global scrope chain can't be garbage collected as long as an inner function or inner functions can access them.

    Possibly memory garbage collection could be optimized to collect memory used by values that no inner function that continues to exist actually accesses, but I had no further information - see helpful comments.