Convention-based approach

JavaScript objects do not care about privacy. All the properties and methods are publicly accessible if no caution is taken. So, if we want to avoid access to some properties or methods concerning internal implementation details, we have to set up a strategy.

A first simple approach consists in adopting convention-based naming for internal members of an object. For example, internal members can have a name starting with a prefix, such as the underscore (_) character. Let's explain with an example:

function TheatreSeats() { 
  this._seats = []; 
} 
 
TheatreSeats.prototype.placePerson = function(person) { 
  this._seats.push(person); 
}; 

This code defines a constructor for objects that represent seats in a theatre where a person can ...

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.