object.freeze
One of my favorite part of JavaScript has always been mutability of objects. I loved that MooTools and likewise frameworks could modify native prototypes to enhance them with functionality we knew the language need; in fact, I credit MooTools with pushing the web forward.
我最喜欢JavaScript部分之一一直是对象的可变性。 我喜欢MooTools和类似的框架可以修改本机原型,以使用我们知道语言需要的功能来增强它们。 实际上,我认为MooTools推动了网络的发展。
There are cases, however, where you don't want an object to be modifiable; you don't want values for existing properties to be changed, added, or removed. That's where Object.freeze
can help -- with Object.freeze
you can create immutable objects you can trust!
但是,在某些情况下,您不希望对象是可修改的。 您不希望更改,添加或删除现有属性的值。 这就是Object.freeze
可以提供帮助的地方-通过Object.freeze
您可以创建可以信任的不可变对象!
const obj = Object.freeze({ x: 1, y: 2});// None of these do anythingobj.x = 8; // { x: 1, y: 2}delete obj.x; // { x: 1, y: 2}obj.z = 3; // { x: 1, y: 2}
Object.freeze
is a welcomed addition to JavaScript and a necessary one. If you have objects whose integrity you want to secure, immutability is required. Object.seal
provides similar functionality without the ability to freeze values, so Object.freeze
is your best choice when you want to lock down an object!
Object.freeze
是JavaScript的受欢迎补充,也是必需的。 如果您要保护其完整性的对象,则必须具有不变性。 Object.seal
提供了类似的功能,但没有冻结值的功能,因此当您想要锁定对象时, Object.freeze
是您的最佳选择!
翻译自:
object.freeze