liveBook · Manning

Private member

As explained in Web Components in Action

A private member is a program element whose direct access is restricted to its defining class, module, file, or other language-defined scope.

Private members help protect a component’s internal workings from unintended use. JavaScript underscores can signal that a member is internal, but they restrict access by convention, not by language enforcement. section 8.1 section 3.2

Internal method versus public API

A component’s add() method updates its data model and then calls addItemToUI(). Calling addItemToUI() directly can add an element that disappears when the component redraws. Use the intended API rather than an internal method. section 8.1

Listing 3.7. Getters and setters for our component’s configurable options
set apiKey(value) {            #1
   this._apiKey = value;
   this.doSearch();
}

set searchTerm(value) {        #2
   this._searchTerm = value;
   this.doSearch();
}

The setters expose apiKey and searchTerm while storing values in underscore-prefixed fields. section 3.2

How Web Components in Action covers it

How deep it goes
Distinguishes convention-based privacy from actual restriction and illustrates the risks of calling an internal method.
Examples
Uses addItemToUI() versus add() and underscore-prefixed fields such as _searchTerm.
What you can do after
Evaluate component APIs by distinguishing intended public methods from internal implementation details.
How it connects
Connects private members with encapsulation, Web Components, getters and setters, and JavaScript class fields.

Also explained in

Compare how 12 books explain private member →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.