- Mastering JavaScript Object-Oriented Programming
- Andrea Chiarelli
- 274字
- 2021-07-14 11:24:32
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.
- Android Jetpack開發(fā):原理解析與應(yīng)用實(shí)戰(zhàn)
- 自己動手實(shí)現(xiàn)Lua:虛擬機(jī)、編譯器和標(biāo)準(zhǔn)庫
- Java入門很輕松(微課超值版)
- 征服RIA
- 深度強(qiáng)化學(xué)習(xí)算法與實(shí)踐:基于PyTorch的實(shí)現(xiàn)
- iOS編程基礎(chǔ):Swift、Xcode和Cocoa入門指南
- Mastering JBoss Enterprise Application Platform 7
- Python機(jī)器學(xué)習(xí)算法: 原理、實(shí)現(xiàn)與案例
- 0 bug:C/C++商用工程之道
- Go語言開發(fā)實(shí)戰(zhàn)(慕課版)
- FFmpeg開發(fā)實(shí)戰(zhàn):從零基礎(chǔ)到短視頻上線
- Mastering Embedded Linux Programming
- 一步一步學(xué)Spring Boot:微服務(wù)項(xiàng)目實(shí)戰(zhàn)(第2版)
- Visual C++程序設(shè)計(jì)全程指南
- Mastering Swift 4(Fourth Edition)