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.

JavascriptData Integrity

Code

javascriptsnippet
31 lines
// `#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: false

How 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

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`.