我想在 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/