You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This document provides an opinionated list of code conventions and patterns for writing classes in modern JavaScript.
The aim is to establish a contract between the Consumer, the Provider, and developers, focusing on intention. Some property types have a stronger contract than others.
Implementing Protected Members in JavaScript by Hacking Symbols and Private Fields
Implementing Protected Members in JavaScript Classes
Introduction
In many object-oriented languages, the concept of protected members allows properties and methods to be accessible within the class they are defined, as well as by subclasses. JavaScript, however, does not natively support protected members. This article introduces a novel approach to simulate protected access in JavaScript classes using symbols and private fields.
The Challenge
JavaScript provides private fields, but they are not accessible to any derived classes. This limitation means that developers cannot use private fields to directly implement protected members, which are a staple in many other object-oriented languages.
One Solution
The solution involves using symbols as keys for protected properties and methods, ensuring that only the class and its subclasses have access to them. This is achieved by: