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

标签 javascript ecmascript-6 es6-class

我想在 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) }

关于javascript - 是否可以自动密封JS对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58470349/

相关文章:

javascript - 将ace代码编辑器导入webpack、es6、typescript项目

node.js - Mocha 无法识别动态导入

javascript - JS 递归检查对象字段(+嵌套)为 false/true

javascript - 如何为 sessionStorage 编写合适的 ES6 包装器

javascript - 类型错误 : 'set' on proxy: trap returned falsish for property

javascript - LinkedIn 共享显示大图像的要求

javascript - 防止 textArea 缩小空格

javascript - mouseenter 和 mouseleave 函数的一些问题

javascript - 附加触摸事件库

javascript - 如何防止类继承静态变量?