Javascript:对象不支持方法' freeze' [英] Javascript: Object doesn't support method 'freeze'

查看:244
本文介绍了Javascript:对象不支持方法' freeze'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Javascript创建枚举. 使用的javascript代码是

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

调用方法 Object.freeze(FeatureName)时,该方法对于除IE7和IE8以外的所有浏览器都适用.除此之外,还有其他选择吗?

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?

推荐答案

John Resig提供了一种替代方法.我没有在您提到的浏览器中尝试过.试试看,让我们知道.

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

这篇关于Javascript:对象不支持方法&amp;#39; freeze&amp;#39;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆