0 day streak
javascript / intermediate
Snippet

Data Encapsulation using Private Properties and Accessors in Services

Private class fields (#) enforce strict hard privacy at runtime in JavaScript. Combined with getters and setters, services can cleanly encapsulate sensitive state and guard state modifications with validation rules.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class SessionManager {
#authToken: string | null = null;
get isAuthenticated(): boolean {
return this.#authToken !== null;
}
set authToken(token: string) {
if (!token.trim()) {
throw new Error('Token cannot be empty');
}
this.#authToken = token;
}
clearSession(): void {
this.#authToken = null;
}
}
angular
Breakdown
1
#authToken: string | null = null;
Declares a true JavaScript private field that cannot be accessed or modified from outside the class instance.
2
get isAuthenticated(): boolean {
Provides read-only access to derived state without exposing the internal token directly.
3
set authToken(token: string) {
Intercepts write operations on the property to perform input validation before updating private state.