In JavaScript, the object's extensible property is used to indicate whether new properties are allowed to be added dynamically in the object. In the ECMAScript 3 standard, all objects are extensible. In the ECMAScript 5 standard, all objects are still extensible by default, but this property can be changed by setting.
To check whether an object is extensible, you can use the Object.isExtensible() statement:
The code copy is as follows:
var o = {x:1};
console.log(Object.isExtensible(o));//true
To make an object that is not extensible, you can use the Object.preventExtensions() statement:
The code copy is as follows:
Object.preventExtensions(o)
console.log(Object.isExtensible(o));//false
It is worth noting that since there is no inverse operation statement of Object.preventExtensions(), once an object is set to non-extensible, there is no way to set it to extend again.
The scope of the Object.preventExtensions() statement is the object itself, and the prototype object is not affected. If an object is set to non-extensible, properties can still be added dynamically in its prototype object, and these dynamically added properties can still be inherited by the object.
Object.seal() and Object.freeze()
Object.preventExtensions() prevents new properties from being added dynamically in objects. In addition to this operation, there are two more stringent operations in JavaScript to protect objects: Object.seal() and Object.freeze().
The function of Object.seal() is to set the configurable property of all objects' own property to false on the basis of Object.preventExtensions(). Like the Object.preventExtensions() operation, Object.seal() has no anti-operation, so the object cannot be restored once it seals. In JavaScript, you can use Object.isSealed() to query whether an object has been sealed.
The function of Object.freeze() is to set the property of all objects as read-only based on Object.seal(). Like the Object.seal() and Object.preventExtensions() operations, Object.freeze() has no anti-operation, so the object cannot be restored once it is freezen. In JavaScript, you can use Object.isFrozen() to query whether an object has been freezen.
The code copy is as follows:
console.log(Object.isSealed(o));//false
Object.seal(o);
console.log(Object.isSealed(o));//true
console.log(Object.isFrozen(o));//false
Object.freeze(o);
console.log(Object.isFrozen(o));//true
Whether it is Object.preventExtensions(), Object.seal() and Object.freeze(), its scope of action is the object itself, and the object's prototype object will not be affected.