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 ...

Get Mastering JavaScript Object-Oriented Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.