// main.js —— const 冻结的是绑定,不是对象内容 // 模块处于严格模式,所以对 const 重新赋值/写冻结属性都会抛 TypeError。 export function reassignConst() { const o = { n: 1 }; let error = null; try { o = { n: 2 }; // eslint-disable-line no-const-assign } catch (e) { error = e.constructor.name; } return { n: o.n, error }; } export function mutateConstContents() { const o = { n: 1 }; o.n = 2; o.extra = true; return { n: o.n, extra: o.extra }; } export function constArray() { const a = [1]; a.push(2); let error = null; try { a = []; // eslint-disable-line no-const-assign } catch (e) { error = e.constructor.name; } return { contents: a.join(','), error }; } export function freezeIsShallow() { const o = Object.freeze({ n: 1, inner: { n: 10 } }); let topError = null; let innerError = null; try { o.n = 2; // 冻结属性,严格模式下抛错 } catch (e) { topError = e.constructor.name; } try { o.inner.n = 20; // 内层对象没有被冻结 } catch (e) { innerError = e.constructor.name; } return { n: o.n, innerN: o.inner.n, topError, innerError, frozen: Object.isFrozen(o) }; } export function run(log = console.log) { const r1 = reassignConst(); const r2 = mutateConstContents(); const r3 = constArray(); const r4 = freezeIsShallow(); const rows = [ ['const 对象重新赋值', `n=${r1.n}, error=${r1.error}`], ['const 对象修改属性', `n=${r2.n}, extra=${r2.extra}`], ['const 数组 push', `contents=${r3.contents}, 重新赋值 error=${r3.error}`], ['Object.freeze 后写顶层属性', `n=${r4.n}, error=${r4.topError}`], ['Object.freeze 后写内层属性', `innerN=${r4.innerN}, error=${r4.innerError}`], ['Object.isFrozen', String(r4.frozen)], ]; log('场景 => 结果'); for (const [label, value] of rows) log(`${label} => ${value}`); log('-'.repeat(50)); log('要点:const 只保证「绑定不变」;对象内容默认可变。Object.freeze 是浅冻结,嵌套对象仍可修改。'); return rows; }