Difference between freeze and seal

后端 未结 8 1010
孤独总比滥情好
孤独总比滥情好 2020-12-07 08:00

I just heard about the JavaScript methods freeze and seal, which can be used to make any Object immutable.

Here\'s a short example how to u

8条回答
  •  无人及你
    2020-12-07 08:24

    Object.seal

    • It prevents adding and/or removing properties from the sealed object; using delete will return false
    • It makes every existing property non-configurable: they cannot be converted from 'data descriptors' to 'accessor descriptors' (and vice versa), and no attribute of accessor descriptors can be modified at all (whereas data descriptors can change their writable attribute, and their value attribute if writeable is true).
    • Can throw a TypeError when attempting to modify the value of the sealed object itself (most commonly in strict mode)

    Object.freeze

    • Exactly what Object.seal does, plus:
    • It prevents modifying any existing properties

    Neither one affects 'deep'/grandchildren objects. E.g., if obj is frozen, obj.el can’t be reassigned, but the value of obj.el could be modified, e.g. obj.el.id can be changed.


    Performance:

    Sealing or freezing an object may affect its enumeration speed, depending on the browser:

    • Firefox: enumeration performance is not impacted
    • IE: enumeration performance impact is negligible
    • Chrome: enumeration performance is faster with sealed or frozen objects
    • Safari: sealed or frozen objects enumerate 92% slower (as of 2014)

    Tests: Sealed objects, Frozen objects.

提交回复
热议问题