实现说明
演示用的数据放在这几个模块级绑定中:ext、sealed、frozen。
使用要点
- 每一步打印都带着自己的标签:
preventExtensions keys:、sealed write ok:、sealed keys intact:。
常见问题
这个示例需要哪些包?
一个都不用。代码用到的符号都在标准库里解析。 文件的状态由几个模块级绑定持有:ext、sealed、frozen。
核心语句
sealed.a = 9; // seal still allows value writes: the in-place change succeeds
console.log('sealed write ok:', sealed.a === 9);
ext.b = 2; // throws TypeError in strict mode, silently fails otherwise
} catch {
// adding a key is blocked
}
const ext = Object.preventExtensions({ a: 1 });
代码示例
// three gradations: preventExtensions only blocks new keys; seal also blocks deletions; freeze also blocks value writes
const ext = Object.preventExtensions({ a: 1 });
try {
ext.b = 2; // throws TypeError in strict mode, silently fails otherwise
} catch {
// adding a key is blocked
}
console.log('preventExtensions keys:', Object.keys(ext).join(','));
const sealed = Object.seal({ a: 1 });
sealed.a = 9; // seal still allows value writes: the in-place change succeeds
console.log('sealed write ok:', sealed.a === 9);
try {
delete sealed.a; // the deletion is blocked
} catch {
// the deletion is blocked
}
console.log('sealed keys intact:', Object.keys(sealed).join(','), 'isSealed:', Object.isSealed(sealed));
const frozen = Object.freeze({ a: 1 });
try {
frozen.a = 9; // the value write is blocked
} catch {
// the write is blocked
}
console.log('frozen value kept:', frozen.a === 1, 'isFrozen:', Object.isFrozen(frozen));
console.log('still extensible :', Object.isExtensible(frozen), Object.isExtensible(sealed), Object.isExtensible(ext));