JAVA SCRIPT - Preventing Object Extensibility

Preventing Object ExtensibilitY


Problem

You want to prevent others from extending an object. 

Solution

Use the ECMAScript 5 Object.preventExtensions() method to lock an object against future property additions: 


'use strict';
var Test = {
 value1 : "one",
 value2 : function() {
 return this.value1;
 }
};
try {
 Object.preventExtensions(Test);
 // the following fails, and throws a TypeError in Strict mode
 Test.value3 = "test";
} catch(e) {
 console.log(e);
}


EXPLAIN 


The Object.preventExtensions() method prevents developers from extending the object with new properties, though property values themselves are still writable. It sets an internal property, Extensible, to false. You can check to see if an object is extensible using Object.isExtensible:


if (Object.isExtensible(obj)) {
 // extend the object
}


If you attempt to add a property to an object that can’t be extended, the effort will either fail silently, or, if strict mode is in effect, will throw a TypeError exception:

TypeError: Can't add property value3, object is not extensible

Though you can’t extend the object, you can edit existing property values, as well as modify the object’s property descriptor.

0 comments:

Post a Comment