javascript / expert
Snippet
Secure Brand Checking with Private Fields
Using the 'in' operator with private class fields provides a highly secure 'Brand Check'. Unlike 'instanceof', it cannot be faked by manipulating prototypes and is robust against cross-realm issues (e.g., multiple Node.js VM contexts), ensuring strict internal identity.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class SecureToken {#brand;constructor() { this.#brand = true; }static isToken(obj) {try {return #brand in obj;} catch {return false;}}}const valid = new SecureToken();console.log(SecureToken.isToken(valid)); // trueconsole.log(SecureToken.isToken({ #brand: true })); // Syntax Error / False
nodejs
Breakdown
1
return #brand in obj;
Attempts to access a private field to verify the object was created by this specific class.
2
static isToken(obj)
A static utility that acts as a secure guard for type-sensitive operations.