6

I am trying to create an enummeration in Javascript. The javascript code used is

var FeatureName = {
"FEATURE1": 1,
"FEATURE2": 2,
"FEATURE3": 3,
"FEATURE4": 4,
"FEATURE5": 5
}
Object.freeze(FeatureName);

When the method Object.freeze(FeatureName), is called it works fine for all the browsers except IE7 and IE8. Is there any alternative to this?

Anubhav Ranjan
  • 1,558
  • 3
  • 18
  • 32
  • 4
    http://kangax.github.com/es5-compat-table/ compatibility chart – Satish Bellapu Oct 29 '12 at 08:00
  • As shown in [this table](http://kangax.github.com/es5-compat-table/), those browsers are simply too old to support this EcmaScript 5 feature. – kapa Oct 29 '12 at 08:00
  • @Sats: Do you have any idea if I can have any alternative mechanism for Object.freeze or if I can somehow create a method freeze in the prototype of object – Anubhav Ranjan Oct 29 '12 at 08:06

2 Answers2

6

John Resig provides an alternative. I haven't tried it in the browsers you mention. Try it and let us know.

http://ejohn.org/blog/ecmascript-5-objects-and-properties/

Object.freeze = function( obj ) {
  var props = Object.getOwnPropertyNames( obj );

  for ( var i = 0; i < props.length; i++ ) {
    var desc = Object.getOwnPropertyDescriptor( obj, props[i] );

    if ( "value" in desc ) {
      desc.writable = false;
    }

     desc.configurable = false;
     Object.defineProperty( obj, props[i], desc );
  }

  return Object.preventExtensions( obj );
};
ColBeseder
  • 3,579
  • 3
  • 28
  • 45
  • The problem is that the methods this implementation uses are not available in IE8 (and of course IE7). – kapa Oct 29 '12 at 08:11
  • @ColBeseder: Tried, but no use. It did create the prototype method but now has got the error "Object doesn't support property or method 'getOwnPropertyNames'". – Anubhav Ranjan Oct 29 '12 at 08:13
  • 2
    Just create a dummy like function() {}. That will make the error go away, and you can continue your life hoping that your javascript does not depend on the freeze function actually doing anything ... – oligofren Feb 19 '13 at 14:05
5

You can add include the es5-sham "monkey-patch" (only need to include es5-sham.min.js) on your page, but it's important to understand that this will simply prevent the error from appearing.

It's not a true polyfill though; from the project's README on Github:

Object.freeze

Silently fails on all legacy engines. This should be fine unless you are depending on the safety and security provisions of this method, which you cannot possibly obtain in legacy engines.

This library is also available from cdnjs if you want to use a CDN.

You can include it with code like this (note the tags limiting it to IE version 8 and older):

<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/es5-shim/4.0.5/es5-sham.min.js" type="text/javascript"></script>
<![endif]-->
Alexander
  • 2,320
  • 2
  • 25
  • 33