gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:56:17 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com