PRIVATE VARIABLES
Strictly speaking, JavaScript has no concept of private members; all object properties are public. There is, however, a concept of private variables. Any variable defined inside a function or block is considered private because it is inaccessible outside that function. This includes function arguments, local variables, and functions defined inside other functions. Consider the following:
function add(num1, num2) {
let sum = num1 + num2;
return sum;
}
In this function, there are three private variables: num1
, num2
, and sum
. These variables are accessible inside the function but can't be accessed outside it. If a closure were to be created inside this function, it would have access to these variables through its scope chain. Using this knowledge, you can create public methods that have access to private variables.
A privileged method is a public method that has access to private variables and/or private functions. There are two ways to create privileged methods...