admin管理员组文章数量:1290089
Javascript has Object.seal()
to prevent any extensions to an object (and Object.freeze()
to completely freeze it). But it also has Object.preventExtensions()
that seems to do the same job as Object.seal()
, aside from some really small implementation differences.
In what situations would I want/need to use Object.preventExtensions()
rather than Object.seal()
?
Javascript has Object.seal()
to prevent any extensions to an object (and Object.freeze()
to completely freeze it). But it also has Object.preventExtensions()
that seems to do the same job as Object.seal()
, aside from some really small implementation differences.
In what situations would I want/need to use Object.preventExtensions()
rather than Object.seal()
?
2 Answers
Reset to default 4Object.seal()
does everything that Object.preventExtensions()
does, but adds additional restrictions. From MDN:
The
Object.seal()
static method seals an object. Sealing an object prevents extensions and makes existing properties non-configurable. A sealed object has a fixed set of properties: new properties cannot be added, existing properties cannot be removed, their enumerability and configurability cannot be changed, and its prototype cannot be re-assigned. Values of existing properties can still be changed as long as they are writable.
Compare this with the description of Object.preventExtensions():
The
Object.preventExtensions()
static method prevents new properties from ever being added to an object (i.e. prevents future extensions to the object). It also prevents the object's prototype from being re-assigned.
The difference is that seal()
adds:
- properties can't be removed
- property configurations can't be changed (e.g. you can't make a read-only property writable)
Both are used to implement "defensive programming", which attempts to protect data from program bugs. And in the case of client-side JavaScript, it may also protect against deliberate code injections. preventExtensions()
just protects against addition of properties dynamically, while seal()
protects against most attempts to change the properties.
Object.preventExtensions()
makes it impossible to add new properties to an object, but it does not prevent values of existing properties from being updated. Object.seal()
makes all the properties of an object not configurable and not writable in addition to preventing extensions. Also, Object.preventExtensions()
does not disallow property deletion.
本文标签: javascriptWhen would I need ObjectpreventExtensions()Stack Overflow
版权声明:本文标题:javascript - When would I need `Object.preventExtensions()`? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741467295a2380386.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论