Mastering JavaScript Object-Oriented Programming
上QQ阅读APP看书,第一时间看更新

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 prefix indicates that it should be considered an internal property. Of course, it is just a convention—the developer should know that members of an object whose names start with the underscore character are for internal use.

However, there is no technical obstacle to prevent a developer using that member. The internal details are not really hidden and privacy is based on the developer's willingness. Apart from this, the convention—based approach has some other drawbacks. For example, it pollutes the public interface with members that should not be used, breaking the principle that using an object should be simple. Moreover, it can lead to property clashes when using inheritance.

Even if this approach can appear simple, it has been widely used by common JavaScript libraries such as jQuery and Backbone.js.