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:
1
2
3
| Object.preventExtentions( " Your Object name " ); Object.isExtensible( " Your object name " ); // it will return Boolean value (true/false) |
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
1
2
3
4
5
6
7
8
9
| 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" |
You can still delete properties in above example
1
2
3
4
5
6
7
| delete record.author; //result: true record.author; //result: undefined |
You can also see the example live on NodeJS Console: http://www.node-console.com/script/javascript-object-protection-using-prevent-extensions
2. Sealing
1
2
3
| Object.seal( " Your Object Name" ); Object.isSealed(record); //return boolean value true/false |
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:
1
2
3
4
5
| Object.getOwnPropertyDescriptor(record, 'id' ); Object.sealing(obj); Object.getOwnPropertyDescriptor(record, 'id' ); |
Though we can still change the property ‘id':
1
| record.id=89; |
but the changes to attributes cannot be made:
1
| Object.defineProperty(record, 'id' ,{enumerable: false }); |
Result: cannot redefine property ‘id’
Example live on NodeJS Console: http://www.node-console.com/script/javascript-object-protection-using-sealing
3. Freezing
1
| Objects.freeze( " your object name " ); |
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 .
1
2
3
4
5
6
7
8
9
| var record={id:17,author: "sahil" }; Object.freeze(record); record.id=20; console.log(record.id) // it will print 17 |
Checking whether object is frozen
1
| Object.freeze( " your object name " ); |
To see it live, visit: http://www.node-console.com/script/javascript-object-protection-using-freezing
No comments:
Post a Comment
If you have any doubts or questions, please let us know.