是否可以自动密封JS对象?

is it possible to seal JS objects automatically?

我想在 JavaScript 个对象创建后立即密封它们:

'use strict';

class Test {
}

const t = Object.seal(new Test());
t.p = true; // error!

有没有办法自动完成,如下所示?

Test.sealInstances = true // I wish sealInstances was real!
const t = new Test();
t.p = true; // error

我知道我可以做到:

function createTest() {
  return Object.seal(new Test())
}

并在任何地方使用 createTest,但我更喜欢 new Test() 语法。

在构造函数中放入Object.seal即可:

'use strict';

class Test {
  constructor() {
    Object.seal(this);
  }
}

const t1 = new Test();
const t2 = new Test();
try {
  t1.p = 'p';
} catch(e) { console.log(e.message) }
try {
  t2.z = 'z';
} catch(e) { console.log(e.message) }