Protecting Objects In JavaScript

19 / Sep / 2013 by Sahil Chitkara 0 comments

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:

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

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

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

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:

Object.getOwnPropertyDescriptor(record,'id');

Object.sealing(obj);

Object.getOwnPropertyDescriptor(record,'id');

Though we can still change the property ‘id':

record.id=89;

but the changes to attributes cannot be made:

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

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 .

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

Object.freeze(" your object name ");

To see it live, visit: http://www.node-console.com/script/javascript-object-protection-using-freezing

FOUND THIS USEFUL? SHARE IT

Leave a comment -