Javascript: Object doesn't support method 'freeze'

一曲冷凌霜 提交于 2019-11-29 10:48:33

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

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