javascript / intermediate
Snippet
Encapsulating Data with Private Class Fields
Private class fields (marked with #) ensure that sensitive data or internal helper methods cannot be accessed or modified from outside the class instance.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class ApiService {#apiKey;constructor(key) {this.#apiKey = key;}#buildHeaders() {return { 'Authorization': `Bearer ${this.#apiKey}` };}async fetchData(url) {const headers = this.#buildHeaders();return fetch(url, { headers });}}
nodejs
Breakdown
1
#apiKey;
Declares a private field that is not accessible via instance property lookup.
2
#buildHeaders()
Defines a private method that can only be called from within other methods of the same class.