在JavaScript中有使用常量的方法吗?

如果不是,指定用作常量的变量的常见做法是什么?


当前回答

在JavaScript中引入常量充其量是一种hack。

在JavaScript中创建持久且全局可访问的值的一个好方法是声明一个具有“只读”属性的对象文字,如下所示:

            my={get constant1(){return "constant 1"},
                get constant2(){return "constant 2"},
                get constant3(){return "constant 3"},
                get constantN(){return "constant N"}
                }

你可以将你所有的常量组合在一个单独的“my”附属对象中,在那里你可以查找你存储的值或其他任何你决定放在那里的东西。现在让我们来测试一下它是否有效:

           my.constant1; >> "constant 1" 
           my.constant1 = "new constant 1";
           my.constant1; >> "constant 1" 

正如我们所看到的,“我的”。Constant1”属性保留了其原始价值。你已经为自己设置了一些不错的“绿色”临时常数……

当然,这只能防止您意外地修改、修改、无效或清空您的属性常量值,就像在给定的例子中那样。

否则我仍然认为常数是傻瓜用的。 我仍然认为,用你巨大的自由换取一个小小的欺骗性的安全是最糟糕的交易。

其他回答

您是否试图保护变量不被修改?如果是,那么你可以使用模块模式:

var CONFIG = (function() {
     var private = {
         'MY_CONST': '1',
         'ANOTHER_CONST': '2'
     };

     return {
        get: function(name) { return private[name]; }
    };
})();

alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1

CONFIG.MY_CONST = '2';
alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1

CONFIG.private.MY_CONST = '2';                 // error
alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1

使用这种方法,不能修改值。但是,你必须在CONFIG:(上使用get()方法。

如果您不需要严格保护变量值,那么只需按照建议执行并使用ALL CAPS约定即可。

在可能的情况下将常量分组到结构中:

例如,在我目前的游戏项目中,我使用了以下方法:

var CONST_WILD_TYPES = {
    REGULAR: 'REGULAR',
    EXPANDING: 'EXPANDING',
    STICKY: 'STICKY',
    SHIFTING: 'SHIFTING'
};

任务:

var wildType = CONST_WILD_TYPES.REGULAR;

比较:

if (wildType === CONST_WILD_TYPES.REGULAR) {
    // do something here
}

最近我用的是:

switch (wildType) {
    case CONST_WILD_TYPES.REGULAR:
        // do something here
        break;
    case CONST_WILD_TYPES.EXPANDING:
        // do something here
        break;
}

IE11是新的ES6标准,有“const”声明。 以上内容适用于IE8、IE9和IE10等早期浏览器。

显然,这表明需要一个标准化的跨浏览器const关键字。

但现在:

var myconst = value;

or

Object['myconst'] = value;

两者似乎都足够了,其他的就像用火箭筒打苍蝇一样。

从ES2015开始,JavaScript有了const的概念:

const MY_CONSTANT = "some-value";

这将工作在几乎所有的浏览器除了ie8, 9和10。有些可能还需要启用严格模式。

如果你需要支持旧的浏览器或使用遗留代码,你可以使用var和像ALL_CAPS这样的约定来表明某些值不应该被修改:

var MY_CONSTANT = "some-value";

您可以轻松地为脚本配备一种用于常量的机制,这些常量可以设置但不能更改。试图更改它们将产生错误。

/* author Keith Evetts 2009 License: LGPL  
anonymous function sets up:  
global function SETCONST (String name, mixed value)  
global function CONST (String name)  
constants once set may not be altered - console error is generated  
they are retrieved as CONST(name)  
the object holding the constants is private and cannot be accessed from the outer script directly, only through the setter and getter provided  
*/

(function(){  
  var constants = {};  
  self.SETCONST = function(name,value) {  
      if (typeof name !== 'string') { throw new Error('constant name is not a string'); }  
      if (!value) { throw new Error(' no value supplied for constant ' + name); }  
      else if ((name in constants) ) { throw new Error('constant ' + name + ' is already defined'); }   
      else {   
          constants[name] = value;   
          return true;  
    }    
  };  
  self.CONST = function(name) {  
      if (typeof name !== 'string') { throw new Error('constant name is not a string'); }  
      if ( name in constants ) { return constants[name]; }    
      else { throw new Error('constant ' + name + ' has not been defined'); }  
  };  
}())  


// -------------  demo ----------------------------  
SETCONST( 'VAT', 0.175 );  
alert( CONST('VAT') );


//try to alter the value of VAT  
try{  
  SETCONST( 'VAT', 0.22 );  
} catch ( exc )  {  
   alert (exc.message);  
}  
//check old value of VAT remains  
alert( CONST('VAT') );  


// try to get at constants object directly  
constants['DODO'] = "dead bird";  // error