WeakMap For Instance-Private Data

Hide instance state in a module-scoped WeakMap so properties stay unreachable from outside while garbage collection stays automatic.

JavascriptSecurity Boundaries

Code

javascriptsnippet
22 lines
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

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