This is the 25th day of my participation in the August Wen Challenge.More challenges in August
invariance
Sometimes we want properties or objects to be immutable. In ES5, there are many ways to do this, but all of them create shallow immutability, that is, they only affect the target object and its immediate properties. If the target object references other objects (arrays, objects, functions, and so on), the contents of the other objects are unaffected and remain mutable.
myImmutableObject.foo;/ / [1, 2, 3]
myImmutableObject.foo.push(4);
myImmutableObject.foo;/ / [1, 2, 3, 4].
Copy the code
Assume that the myImmutableObject in the code has been created and is immutable, but to protect its contents, myimMutableObjec.foo, use the following method to make foo immutable as well.
Object is constant
With the writable: false and different: false, you can create a constant property that cannot be modified, redefined, or deleted:
var myObject={};
Object.defineProperty(myObject,"FAVORITE_NUMBER", {value:2.writable:false.configurable:false
});
Copy the code
Prohibit extensions
To prevent an Object from adding new properties and keeping existing ones, use object.preventExtensions ():
var myObject = {
a : 2
};
Object.preventExtensions(myObject);
myObject.b = 3;
myObject.b;//undefined
Copy the code
In non-strict mode, creating B silently fails, and in strict mode, TypeError is thrown.
seal
Object.seal() creates a “sealed” Object. This method actually maps to Object.preventExtensions() on an existing Object and marks all existing properties as signals :false. So, not only can you not add new attributes, you can’t reconfigure or delete any existing attributes (but you can change their values)
freeze
Object.freeze() creates a frozen Object. This method actually calls Object.seal on an existing Object and marks all “data access” properties as writable:false, so that their values cannot be changed.
This method is the highest level of immutability that can be applied to an object, and it forbids changes to the object itself or any of its immediate attributes (although it still does not affect other objects referenced by the object).
“Deep freeze” an Object: Call Object.freeze() on that Object, then iterate over all the objects it references and call Object.freeze() on those referenced objects. But this can inadvertently freeze other shared objects.