Introduction to extensible attributes of objects in JavaScript, javascript objects
In JavaScript, the extensible attribute of an object is used to indicate whether a new property can be dynamically added to an object. In ECMAScript 3, all objects are extensible. In the ECMAScript 5 standard, all objects are still extensible by default, but this attribute can be changed through settings.
To query whether an Object is extensible, you can use the Object. isExtensible () Statement:
Copy codeThe Code is as follows:
Var o = {x: 1 };
Console. log (Object. isExtensible (o); // true
To make an Object not extensible, you can use the Object. preventExtensions () Statement:
Copy codeThe Code is as follows:
Object. preventExtensions (o)
Console. log (Object. isExtensible (o); // false
It is worth noting that, because there is no anti-operation statement for Object. preventExtensions (), once an Object is set to non-extensible, there is no way to set it to extensible again.
The range of the Object. preventExtensions () statement is the Object itself, and the prototype Object is not affected. If an object is set to non-extensible, the property can still be dynamically added to the prototype object, and the dynamically added property can still be inherited by the object.
Object. seal () and Object. freeze ()
Object. preventExtensions () can prevent dynamic addition of new properties to objects. In addition to this operation, there are two more stringent operations in JavaScript to protect objects: Object. seal () and Object. freeze ().
Object. seal () is used to set the retriable attribute of all Object properties to false Based on Object. preventExtensions. Like the Object. preventExtensions () operation, Object. seal () has no inverse operation. Therefore, once the Object is seal, its status cannot be restored. In JavaScript, you can use Object. isSealed () to query whether an Object is seal.
Object. freeze () is used to set the property of all objects to read-only based on Object. seal. Similar to Object. seal () and Object. preventExtensions () operations, Object. freeze () does not have a reverse operation. Therefore, once the Object is freeze, its status cannot be restored. In JavaScript, you can use Object. isFrozen () to query whether an Object has been freeze.
Copy codeThe Code 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 (), or Object. freeze (), the scope of its function is the Object itself, and the Object's prototype Object will not be affected.