This tutorial will help us about the internal property [[Extensible]].This internal property [[Extensible]] of an object in javascript, is used to specify whether properties can be add to an object or not.Before using the internal property [[Extensible]] we must know which object are extensible and which are not.
1- By default all the user defined objects are extensible.
2- By default all the standard objects in JavaScript are extensible (i.e. Function,Array...etc)
3- Document object may or may not be extensible
1- First we will check if an object is extensible or not if yes the funciton Object.isExtensible(obj) will return true and we can add new properties, else false is returned.
Example:
<script>
var abc = {}; // object defined by user
console.log(Object.isExtensible(abc)); //returned true
var date = new Date(); // date object
console.log(Object.isExtensible(date)); // true
var abc = [88,9,420]; // Array
console.log(Object.isExtensible(abc)); // true
</script>
2- Now we will prevent adding the new properties in an object using function Object.preventExtensions(obj).
Example:
<script>
var abc = {"xyz":420};
Object.preventExtensions(abc);
abc.lm = 85; // adding a new property
document.write(abc.lm); // output: undefined, as addition of property failed
document.write(Object.isExtensible(abc)); // output: false
Note: The parent object is still Extensible hence we can get the new properties from the parent object.
3- Deleting the property of a non-extensible object
Example:
var test = {"xyz":100};
Object.preventExtensions(test);
console.log(Object.isExtensible(test)); // output: false
console.log(test); // output: Object{ xyz: 100 }
delete test["xyz"];
console.log(test); // output: Object{}
4- To Prevent deleting a property of an object we use function Object.seal(obj), this function sets the extensible attribute to false and sets object's own property's attribute that are configurable to false hence the properties can not be deleted.
//object created
var abc = {"prop1":"first", "prop2":"second"};
console.log(Object.getOwnPropertyDescriptor(abc, "prop1"));//output:
Object { configurable=true, enumerable=true, value="first", writable=true}
Object.seal(abc);
console.log(Object.getOwnPropertyDescriptor(abc, "prop1"));
// output: Object { configurable=false, enumerable=true, value="first", writable=true }
console.log(Object.getOwnPropertyDescriptor(abc, "prop2"));
// output: Object { configurable=false, enumerable=true, value="second", writable=true }
console.log(Object.isExtensible(abc)); // output: false
5- Preventing add/delete/write an object using function Object.freeze(obj). The function sets object's extensible attribute to false hence we can not add properties. The function Object.freeze(obj) also sets the object's all, own property's configurable/writable to false hence this will prevent property deletion and editing the value.
0 Comment(s)