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?
Object.freeze()
creates a frozen object, which means it takes an existing object and essentially callsObject.seal()
on it, but it also marks all “data accessor” properties aswritable:false
, so that their values cannot be changed. - Kyle Simpson, You Don't Know JS - This & Object Prototypes