javascript - 是否可以自动密封 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()
更喜欢语法。
解决方案
只需放入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) }
推荐阅读
- postgresql - PostgresSQL 在具有相同列的两个表中排名
- bash - Azure bash CLI - 叉子炸弹会影响天蓝色吗?
- android - Retrofit2 拦截器,仅在特定方法中使用令牌
- python - 硒:点击按钮
- asp.net-core - OpenIddictHandler 在第一次之后不处理 HTTP 请求
- python - 如何从网站导入外部文本文件并使用其中的列表
- python - 想要保持进程直到 subprocess.popen 中的 git 命令完成执行
- plsql - 运行 pl/sql 程序以查找前 10 个素数之和时出错
- c# - PdfSharp 不会更改文件系统信息
- typescript - 离子未捕获(承诺):[对象:对象]