Javascript: Object doesn't support method 'freeze'

主宰稳场 提交于 2019-12-29 07:41:36

问题


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?


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

  return Object.preventExtensions( obj );
};



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


来源:https://stackoverflow.com/questions/13117771/javascript-object-doesnt-support-method-freeze

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!