【问题标题】:is it possible to seal JS objects automatically?是否可以自动密封 JS 对象?
【发布时间】:2020-02-16 14:26:28
【问题描述】:

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

【问题讨论】:

  • 其实工厂函数看起来更干净。在构造函数中使用seal,您将无法再扩展您的类。
  • @georg,在我的例子中,Test 是从模块中导出的。你认为出口工厂是个好主意吗?我的犹豫是,我会失去像const { Test } = require('testModule') 这样方便的语法。
  • 为什么,const {createTest} = require(...) 有什么问题?
  • @georg,确实没有什么问题 :) 也许我会坚持下去,谢谢!

标签: javascript ecmascript-6 es6-class


【解决方案1】:

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

【讨论】:

  • 有趣的是,它需要'use strict' 才能像这样抛出。是否预期/记录在任何地方?
  • 是的,请参阅developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - 尝试删除或向密封对象添加属性,或将数据属性转换为访问器(反之亦然)将失败,无论是静默还是抛出TypeError(最常见,但不是唯一的,在严格模式代码中)。 所以use strict 会导致显式错误,而草率模式会导致静默失败
猜你喜欢
  • 1970-01-01
  • 2023-03-18
  • 2011-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-28
  • 1970-01-01
相关资源
最近更新 更多