I am trying to understand the Object.freeze method of ECMAscript.
My understanding was that it essentially stops changes to all the properties of an object. MDN docu
Set the property descriptors for the object to writable:false
, configurable:false
using Object.defineProprties
; then call Object.preventExtensions
on the object. See How to create static array in javascript.
Object.freeze is a shallow freeze.
If you look at the description in the docs, it says:
Values cannot be changed for data properties. Accessor properties (getters and setters) work the same (and still give the illusion that you are changing the value). Note that values that are objects can still be modified, unless they are also frozen.
If you want to deep-freeze an object, here's a good recursive example
function deepFreeze(o) {
Object.freeze(o);
Object.getOwnPropertyNames(o).forEach(function(prop) {
if (o.hasOwnProperty(prop)
&& o[prop] !== null
&& (typeof o[prop] === "object" || typeof o[prop] === "function")
&& !Object.isFrozen(o[prop])) {
deepFreeze(o[prop]);
}
});
return o;
}
function myObject() {
this.exampleArray = [];
}
var obj = deepFreeze(new myObject());
obj.exampleArray[0] = "foo";
console.log(obj); // exampleArray is unchanged
It's pretty weird, but freezing prevents an element of mutating, adding elements to an array is not mutating (weirdly enough)...
For example in ES6 when you define a variable that won't change you declare it with "const" and not "let". If you say:
const foo = 'foo'; const foo = 'bar;
it will throw an error because you used const. When you say
const foo = ['foo']; foo.append('bar');
it won't throw an error.