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()?

Share Improve this question asked Feb 19 at 22:24 leoleo 8,5417 gold badges54 silver badges87 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 4

Object.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