Protecting Objects In JavaScript
JavaScript is an amazing language. Its like a Lego constructor, depending on different parts you join together, you may get the script you need or just a pile of unwanted codes. Information hiding gets very important when you want to give access to only minimal interface of a module. Depending on the level of protection, this blog discusses each and every level with live examples on NodeJS console, allowing you to check them live and make changes in existing code to see how a change will happen if you insert a few lines of your own code.
Based on level of protection, it can be distinguished in three types:
1. Preventing Extensions:
[js]Object.preventExtentions(" Your Object name ");
Object.isExtensible(" Your object name ");
// it will return Boolean value (true/false)[/js]
After this, it is impossible to add new properties to your prevented object. But one is still able to delete properties of an object. Lets take an Example
[js]var record={id:24,author:"sahil"};
// now we add a new property to Object record
record.title=’javascript’;
console.log(record.title);
// it will print "undefined"[/js]
You can still delete properties in above example
[js]delete record.author;
//result: true
record.author;
//result: undefined[/js]
You can also see the example live on NodeJS Console: http://www.node-console.com/script/javascript-object-protection-using-prevent-extensions
2. Sealing
[js]Object.seal(" Your Object Name");
Object.isSealed(record);
//return boolean value true/false[/js]
Sealing of an object doesn’t allow that object to extend (Prevent Extensions) and also make its properties non-configurable.To check property description for a particular property we can do it by “getOwnPropertyDescriptor”. Example:
[js]Object.getOwnPropertyDescriptor(record,’id’);
Object.sealing(obj);
Object.getOwnPropertyDescriptor(record,’id’);[/js]
Though we can still change the property ‘id’:
[js]record.id=89;[/js]
but the changes to attributes cannot be made:
[js]Object.defineProperty(record,’id’,{enumerable:false});[/js]
Result: cannot redefine property ‘id’
Example live on NodeJS Console: http://www.node-console.com/script/javascript-object-protection-using-sealing
3. Freezing
[js]Objects.freeze(" your object name ");[/js]
Freezing is strongest among all and freezing contains all features of both ‘prevent extensions’ as well as ‘sealing’. After freezing, creation ,deletion and updation of new property/properties is/are not possible .
[js]var record={id:17,author:"sahil"};
Object.freeze(record);
record.id=20;
console.log(record.id)
// it will print 17[/js]
Checking whether object is frozen
[js]Object.freeze(" your object name ");[/js]
To see it live, visit: http://www.node-console.com/script/javascript-object-protection-using-freezing