WeakMap For Instance-Private Data
Hide instance state in a module-scoped WeakMap so properties stay unreachable from outside while garbage collection stays automatic.
Code
const secrets = new WeakMap();
class ApiClient {
constructor(baseUrl, token) {
// 真实凭据不挂到实例属性上:外部 Object.keys 摸不到
secrets.set(this, { baseUrl, token });
}
request(path) {
const { baseUrl, token } = secrets.get(this);
return `${baseUrl}${path} (auth: ${token.slice(0, 4)}...)`;
}
rotateToken(newToken) {
const state = secrets.get(this);
state.token = newToken;
}
}
const client = new ApiClient('https://api.example.com', 's3cr3t-token');
console.log(client.request('/users'));
console.log('own keys:', Object.keys(client)); // 只有原型方法,凭据不可见Inside the snippet
WeakMap For Instance-Private Data keeps everything in the class ApiClient.
Top-level bindings secrets, client hold the demo state — nothing sits inside a function scope.
Using it
The demo output is labeled (own keys:), so every printed line maps back to its originating operation.
Key statements
return `${baseUrl}${path} (auth: ${token.slice(0, 4)}...)`;
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
FAQ
- What does the package manager see?
- An empty dependency file. The snippet imports nothing that needs fetching. Its state lives in module-level bindings: `secrets`, `client`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.