capypad
0 day streak
javascript / expert
Snippet

Robust Branding with Private Fields

Private class fields (#) provide hard encapsulation. 'Branding' is a technique to verify that an object is a specific instance of a class without relying on 'instanceof', which can be spoofed or fail across different execution contexts (iframes).

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class SecurityToken {
#brand;
constructor() { this.#brand = true; }
 
static isToken(obj) {
try {
return !!obj.#brand;
} catch {
return false;
}
}
}
 
const mine = new SecurityToken();
const fake = { #brand: true }; // Syntax Error!
console.log(SecurityToken.isToken(mine)); // true
Breakdown
1
#brand
A private field that is inaccessible outside the class body.
2
obj.#brand
Accessing this on an object that isn't a SecurityToken throws a TypeError, caught here for validation.
3
static isToken(obj)
A static utility to safely verify the internal identity of an object.