O'Reilly logo

Mastering JavaScript Object-Oriented Programming by Andrea Chiarelli

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required