This example works; however, the name attribute is visible, and most importantly mutable. There is nothing to stop a programmer from setting the name attribute to something undesirable such as undefined, even by mistake. This is changed by making “name” a variable instead of an object property inside the Person constructor like this:
It should be noted that the variable re-declaration in this and other examples is not needed. It is present for illustration purposes only. Additional variables should only be declared when they are computed in some fashion. Variables passed as function arguments are long lived!
Now, name is a long-lived variable that is private! This of course, also works with functions.
But what about private static variables? Is that even possible? As it turns out it is. It takes more work to implement, but the general idea is the same.
Starting off, let’s say that we want each instance of Person to have its own unique ID. Even if creating the ID is as simple as incrementing a number, it still requires a static method to keep track of the increment. This needs to be created right away, before any instance of Person is created. Therefore, we need something called a Self-Executing Anonymous Function.
Right now, we have an anonymous function. Even though we are assigning a variable called Person to a function, the function itself does not carry the name Person as part of the constructor. Just for a point of comparison, here is a regular function with a name.
The difference can be seen by logging an instance of each object to the console and viewing the constructor. The constructor of this function has a name: “Person”, whereas the original function has no such name.
Now to make a function self-executing, simply add two parentheses before the final semicolon.
This will log “called” to the console immediately as the page is loaded. This is a great first step. It is here that we can implement our private static variables and methods.
From here, we need to decide whether we need public static immutable methods to access the private static attributes of the object. If we don’t then we just need to return a function with name as part of the constructor arguments.
Here the static method and attribute are private, but accessible to the constructor of the function. But what if we need a public static method that has access to the private static attributes of the object? Instead of simply returning a function, we need to include our static method as a property of the constructor that gets returned. This is accomplished like so:
The function name “init” is not special in any way. This can be named anything.