javascript / expert
Snippet
Robust Instance Validation via Brand Checks
Traditional 'instanceof' checks can be unreliable if objects come from different execution contexts (realms). Private 'brand checks' using the '#field in object' syntax provide a foolproof way to verify that an object is a genuine instance of a class.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Validator {#isValidator = true;static isValidator(obj) {return obj && #isValidator in obj;}validate(data) {return !!data;}}const v = new Validator();console.log(Validator.isValidator(v)); // trueconsole.log(Validator.isValidator({ validate: () => {} })); // false
nodejs
Breakdown
1
#isValidator = true;
Declares a private field that acts as a unique identifier ('brand') for the class.
2
return obj && #isValidator in obj;
Uses the 'in' operator on a private field to perform a crash-proof brand check.
3
Validator.isValidator(...)
Provides a static utility to verify internal class integrity without exposing private data.