liveBook · Manning

Encapsulation

As explained in Web Components in Action

A software design technique that hides an object's internal state and implementation behind a simpler external interface.

Encapsulation wraps a potentially complex object behind a simpler external interface. A Web Component can expose an element, attributes, methods, getters, and setters while managing its own internal behavior. section 8.1

A self-contained object is only half the goal. Good encapsulation also controls access so callers use the component as intended. Privacy may be enforced technically or communicated by convention, such as prefixing internal properties with an underscore. section 8.1 section 8.4

Web Components apply encapsulation in several connected ways:

  • Custom elements provide a simple way to place the component on an HTML page. section 8.1
  • Modules and templates help manage dependencies, while attributes and class-based APIs define intended control points. section 8.1
  • The Shadow DOM protects internal DOM from accidental outside changes, while an open boundary preserves a way to bypass protection when necessary. section 8.4

A component that hides complexity

A page can consume a custom element with a small public API while the element performs complicated internal work. Without a protective boundary, outside code might change its innerHTML or accidentally select one of its buttons; Shadow DOM limits these intrusions. section 8.1 section 15.1

Figure 8.1. Encapsulation means hiding the inner workings of an object, but it often includes choosing how and where to provide access from the outside in.

Use the figure to distinguish an object's hidden inner workings from the deliberate access points exposed to outside code. section 8.1

How Web Components in Action covers it

How deep it goes
Explains interfaces, access protection, conventions, Shadow DOM boundaries, and accidental intrusions, while deferring broader implementation details.
Examples
Demonstrates custom elements, public add methods, external innerHTML changes, and accidental button selection across a component boundary.
What it assumes
Assumes familiarity with HTML and JavaScript classes while introducing encapsulation through custom elements and component APIs.
What you can do after
Apply it via Web Components by designing a public API and protecting internal DOM with an open Shadow DOM boundary.
How it connects
Connects encapsulation with Web Components, custom elements, Shadow DOM, HTML templates, modules, and CSS encapsulation.

Also explained in

Compare how 14 books explain encapsulation →

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.