Privacy levels using closure
A simple way to fix the inconsistencies of the convention-based approach is not using properties for internal members but declaring variables inside the constructor, as shown in the following example:
function TheatreSeats() { var seats = []; this.placePerson = function(person) { seats.push(person); }; }
Using this approach, we can continue to use the constructor as usual preventing the access to the actual internal container-the seats
variable. We are exploiting the internal environment of the TheatreSeats()
function to hide the implementation details and lay the foundations for building the private and public parts of JavaScript objects.
Scope and closure
Before going further, it is useful to make clear some concepts that are used very often in JavaScript programming and on which we will build our approach to implement the information hiding principle. Let's start with the following example:
var greeting = "Good...