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 use it:
var o1 = {}, o2 = {};
Object.freeze(o2);
o1["a"] = "worked";
o2["a"] = "worked";
alert(o1["a"]); //prints "worked"
alert(o2["a"]); //prints "undefined"
What is the difference between freeze
and seal
? Can they increase performance?
delete
will return falsewritable
attribute, and their value
attribute if writeable
is true).TypeError
when attempting to modify the value of the sealed object itself (most commonly in strict mode)Object.seal
does, plus: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.
Sealing or freezing an object may affect its enumeration speed, depending on the browser:
Tests: Sealed objects, Frozen objects.