官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 阜南县| 璧山县| 徐闻县| 朝阳县| 延川县| 措勤县| 郯城县| 杭锦旗| 哈巴河县| 吴川市| 锦州市| 贡嘎县| 江山市| 大邑县| 行唐县| 政和县| 舟山市| 滦平县| 健康| 沿河| 呼伦贝尔市| 福清市| 普定县| 河池市| 榕江县| 鹤山市| 云阳县| 太湖县| 建德市| 任丘市| 上林县| 英超| 沿河| 怀化市| 教育| 景德镇市| 承德县| 绩溪县| 西吉县| 濮阳县| 鹿泉市|