首页 > 解决方案 > 是否可以自动密封 JS 对象?

问题描述

我想在创建 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()更喜欢语法。

标签: javascriptecmascript-6es6-class

解决方案


只需放入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) }


推荐阅读