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
- linked to outer function's scope and have access to its variables, OR
- 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."