Are there other ways to bring privacy to our Objects?


#1

Question

Are there other ways to bring privacy to our Objects?

Answer

As you may know from this lesson on privacy in objects, JavaScript does not have it built in, like other languages, ie. Java, C++.
The main way to convey a sense of privacy is to use underscored properties to signal other developers that the direct value of that property in the object is not to be touched, but what about when that is not enough; it could still be accessed. Another approach that developers use is closures; A closure is a function that is being called inside another function and has access to the state (data created or available ) of the calling function, yet nothing inside that function can be accessed from the outside, except its return. Here is an example, lets say we are using a factory function:

const Robot = (function() { //this is our factory function
    function Robot(name) {   // here we set up an inner function called robot that has a parameter name
        this.getName = function() { // this refers to calling function and it is appending a getName 
            return name;                      // property with a functions that returns name
        };
    }

    return Robot; // we return the function Robot
}()); // we call the function we assigned to the constant Robot

//now when I say: 
const robbie = new Robot('Robbie'); //we create the new robot
console.log('the robot\'s name is: ' + robbie.getName()); // we see the name
delete robbie.name; // we try to delete the name
console.log('Robot\'s name: ' + robbie.getName() + ' stays private.'); // yet .name is inaccessible from the outside

Of course, there can be a catch, which is how much more it makes the computer work every time we were to create a new robot.

Also ES6 has the symbol function, which can help you mainly by increasing access complexity to the value by storing it in an object you don’t get to see and returning a symbol (unique character) that you can use to retrieve it, yet it is not truly private either, since you can access a list of them with the Object.getOwnPropertySymbols function.

Again, there are ways to secure your values, but there is no true privacy (as of yet, or that I know of) in JavaScript Objects,