Private Slots Brand With The in Operator
The in operator with a private field tests the slot itself, so structural branding passes for class instances and fakes with matching public shapes fail.
Code
// `#field in obj` tests the private slot: branding without exposing values.
class AccessToken {
#value;
constructor(value) {
this.#value = value;
}
get charLength() {
return String(this.#value).length;
}
static isAccessToken(value) {
return typeof value === 'object' && value !== null && #value in value;
}
static isSameBrand(candidate) {
// Inside the class body, `in` can check any object for the slot
return typeof candidate === 'object' && candidate !== null && #value in candidate;
}
}
const candidates = [new AccessToken('secret'), {}, { value: 'fake' }, null];
for (const candidate of candidates) {
const branded = AccessToken.isAccessToken(candidate);
console.log(branded ? `token of ${candidate.charLength} chars` : 'not a token');
}
const token = new AccessToken('opensesame');
console.log('same brand:', AccessToken.isSameBrand(token));
console.log('plain object:', AccessToken.isSameBrand({}));Output
Captured from a sandboxed run of this snippet in the build pipeline.
token of 6 chars
not a token
not a token
not a token
same brand: true
plain object: falseHow it works
Private Slots Brand With The in Operator keeps everything in the class AccessToken.
Iteration happens inside for (const candidate of candidates) — everything outside it runs once.
The file’s state is a handful of top-level bindings: candidates, token.
Putting it to use
The demo output is labeled (same brand:, plain object:), so every printed line maps back to its originating operation.
Core lines
return typeof candidate === 'object' && candidate !== null && #value in candidate;
return typeof value === 'object' && value !== null && #value in value;
return String(this.#value).length;
Interactive Tools for This Topic
Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. Its state lives in module-level bindings: `candidates`, `token`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.