javascript / intermediate
Snippet
Encapsulating Data with Private Class Fields
Private class fields (using the # prefix) ensure that sensitive data or internal methods cannot be accessed or modified from outside the class.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class ApiClient {#apiKey;constructor(key) {this.#apiKey = key;}#logRequest(endpoint) {console.log(`Requesting ${endpoint}`);}async fetch(endpoint) {this.#logRequest(endpoint);return fetch(endpoint, { headers: { Authorization: this.#apiKey } });}}
nextjs
Breakdown
1
#apiKey;
Declares a private property that is inaccessible outside the class scope.
2
#logRequest(endpoint) {
Defines a private method for internal class use only.