Saturday, July 9, 2011

How do you make an object final in JavaScript?

­In Java, adding the final modifier to a class prevents the class from being extended.  C# has a similar keyword in sealed.  JavaScript, however, does not have a direct equivalent of this functionality... but its latest version does have some related capabilities. 

There are three functions which provide varying levels of control: 
  • Object.freeze(obj)
  • Object.seal(obj)
  • Object.preventExtensions(obj)

Passing an object into Object.freeze() will keep any new properties (or “methods”, which really are properties) from being added, no existing properties can be deleted, and the values of existing properties can’t be changed. 

Example:
  var x = {height:3, width: 4};
  Object.freeze(x);
  x.color = “red”; // may throw a TypeError exception
  delete(x.width);  // may throw a TypeError or return false
  x.height = 7;  // may throw a TypeError exception
  // x is still {height:3, width:4}



Object.seal() is similar in that no new properties can be added to the object, no existing properties can be deleted… but the values of existing data properties CAN be changed. 

Example:
  var x = {height:3, width: 4};
  Object.seal(x);
  x.color = “red”;  // may throw a TypeError exception
  delete(x.width);  // may throw a TypeError or return false
  x.height = 7;
  // x now is {height:7, width:4}



Finally the least restrictive function is Object.preventExtensions().  It will prevent any new properties from being added, but existing properties can be deleted or modified as normal. 

Example:
  var x = {height:3, width: 4};
  Object.preventExtensions(x);
  x.color = “red”;  // may throw a TypeError exception
  delete(x.width); 
  x.height = 7;
  // x now is {height:7}



These functions are new to the latest version of JavaScript, so they are only available in Firefox 4+, Chrome 6+, and IE 9+.  As of Safari 5 and Opera 11.5, the functions are not yet supported.  

4 comments:

  1. nice! very helpful post. came about it via this thread:

    http://stackoverflow.com/questions/664829/javascript-final-immutable-global-variables

    ReplyDelete
  2. Thank you alot. Came about via the same thread ...

    ReplyDelete