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 these methods and can they increase performance?
You can now force a single object property to be frozen instead of freezing the whole object. You can achieve this with
Object.defineProperty
withwritable: false
as a parameter.In this example,
obj.first
now has its value locked to 99.I was looking at the differences between Freeze and Seal in ECMAScript 5 and created a script to clarify the differences. Frozen creates an immutable object including data and structure. Seal prevents changes to the named interfaces - no adds, deletes - but you can mutate the object and redefine the meaning of its interface.
I wrote a test project which compares these 3 methods:
Object.freeze()
Object.seal()
Object.preventExtensions()
My unit tests cover CRUD cases:
Result:
Object.seal
delete
will return falsewritable
attribute, and theirvalue
attribute ifwriteable
is true).TypeError
when attempting to modify the value of the sealed object itself (most commonly in strict mode)Object.freeze
Object.seal
does, plus:Neither one affects 'deep'/grandchildren objects (e.g. if
obj
is frozen or sealed,obj.el
can't be changed, butobj.el.id
can).Performance:
Sealing or freezing an object may affect its enumeration speed, depending on the browser:
Tests: Sealed objects, Frozen objects.
I know I may be little late but
false
. where as in Sealed writable attribute is set totrue
and rest of the attributes are false.You can always looks these up in MDN. In short: