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 be placed. The intended use is as follows:
var theatreSeats = new TheatreSeats(); theatreSeats.placePerson({name: "John", surname: "Smith"});
The _seats
property is the actual container and its underscore character...