Object.freeze Protects Shared Tables
Object.freeze blocks rewrites on shared tables: in ES modules the mutation attempt throws a TypeError, so defaults survive accidental writes.
Code
// freeze 冻结对象与数组:ESM 严格模式下改写会直接抛 TypeError
const MODES = Object.freeze(['fast', 'safe']);
try {
MODES.push('debug');
} catch (error) {
console.log('array frozen:', error instanceof TypeError);
}
const defaults = Object.freeze({ host: 'localhost', port: 8080 });
try {
defaults.port = 9090;
} catch (error) {
console.log('object frozen:', error instanceof TypeError);
}
console.log('modes intact:', MODES.join(', '));
console.log('port intact:', defaults.port);Output
Captured from a sandboxed run of this snippet in the build pipeline.
array frozen: true
object frozen: true
modes intact: fast, safe
port intact: 8080What to watch for
- Built-in APIs only, so there is no supply chain to vet.
The line that does the heavy lifting:
const defaults = Object.freeze({ host: 'localhost', port: 8080 });
Right behind it in importance:
const MODES = Object.freeze(['fast', 'safe']);
The tail end of the mechanism:
defaults.port = 9090;
Both failed writes sit inside try/catch blocks, and each handler tests error instanceof TypeError before logging — strict-mode ESM turns the mutation attempts MODES.push('debug') and defaults.port = 9090 into exceptions rather than silent no-ops. The final two logs double as assertions: MODES.join(', ') prints fast, safe and defaults.port prints 8080, matching the recorded sampleOutput.
Interactive Tools for This Topic
FAQ
- Is anything beyond the standard library required?
- Nothing beyond the standard library — the snippet is dependency-free.
Report a problem with this exampleOpens a pre-filled issue on GitHub.