`#` symbol to define private class fields and methods in JavaScript.
In this article, we review #
symbol to define private class fields and methods in JavaScript. We will look at:
-
What are private elements?
-
private fields and methods in Ripple codebase.
What are private elements?
Private elements are counterparts of the regular class elements which are public, including class fields, class methods, etc. Private elements get created by using a hash #
prefix and cannot be legally referenced outside of the class. The privacy encapsulation of these class elements is enforced by JavaScript itself. The only way to access a private element is via dot notation, and you can only do so within the class that defines the private element.
Private elements were not native to the language before this syntax existed. In prototypal inheritance, its behavior may be emulated with WeakMap
objects or closures, but they can't compare to the #
syntax in terms of ergonomics. — Mdn docs
Now that we understand what # is used for in field and method names, lets look at how Ripple uses private elements.
private fields and methods in Ripple codebase.
Below is one reference picked from ripple/runtime/array.js, this is for a method named init
#init() {
var proto = RippleArray.prototype;
var array_proto = Array.prototype;
for (const method of introspect_methods) {
proto[method] = function (...v) {
this.$length;
get_all_elements(this);
return array_proto[method].apply(this, v);
};
}
}
Below is another reference picked from the same file, array.js. This is for a variables.
#tracked_elements = [];
#tracked_index;
About me:
Hey, my name is Ramu Narasinga. I study codebase architecture in large open-source projects.
Email: ramu.narasinga@gmail.com
Want to learn from open-source? Solve challenges inspired by open-source projects.
References:
-
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_elements
-
https://github.com/trueadm/ripple/blob/main/packages/ripple/src/runtime/array.js#L67
-
https://github.com/trueadm/ripple/blob/main/packages/ripple/src/runtime/array.js#L39