Skip to content Skip to sidebar Skip to footer

Javascript: Object Doesn't Support Method 'freeze'

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 } Obj

Solution 1:

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 );
  }

  returnObject.preventExtensions( obj );
};

Solution 2:

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]-->

Post a Comment for "Javascript: Object Doesn't Support Method 'freeze'"