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

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


当前回答

我的观点(只适用于对象)。

var constants = (function(){
  var a = 9;

  //GLOBAL CONSTANT (through "return")
  window.__defineGetter__("GCONST", function(){
    return a;
  });

  //LOCAL CONSTANT
  return {
    get CONST(){
      return a;
    }
  }
})();

constants.CONST = 8; //9
alert(constants.CONST); //9

试试!但是要明白,这是对象,而不是简单的变量。

还可以试试:

const a = 9;

其他回答

好吧,这很难看,但它给了我一个在Firefox和Chromium中的常量,一个在Safari和Opera中的非常量(WTF?),以及一个在IE中的变量。

当然eval()是邪恶的,但是没有它,IE会抛出一个错误,阻止脚本运行。

Safari和Opera支持const关键字,但您可以更改const的值。

在本例中,服务器端代码将JavaScript写入页面,用一个值替换{0}。

try{
    // i can haz const?
    eval("const FOO='{0}';");
    // for reals?
    var original=FOO;
    try{
        FOO='?NO!';
    }catch(err1){
        // no err from Firefox/Chrome - fails silently
        alert('err1 '+err1);
    }
    alert('const '+FOO);
    if(FOO=='?NO!'){
        // changed in Sf/Op - set back to original value
        FOO=original;
    }
}catch(err2){
    // IE fail
    alert('err2 '+err2);
    // set var (no var keyword - Chrome/Firefox complain about redefining const)
    FOO='{0}';
    alert('var '+FOO);
}
alert('FOO '+FOO);

这有什么好处?没有太多,因为它不是跨浏览器的。在最好的情况下,至少有些浏览器不允许bookmarklet或第三方脚本修改该值,这可能会让人稍微安心一些。

通过Firefox 2,3,3.6, 4, Iron 8, Chrome 10,12, Opera 11, Safari 5, IE 6,9测试。

有一段时间,我在传递给with()语句的对象字面量中指定了“常量”(实际上仍然不是常量)。我觉得这很聪明。这里有一个例子:

with ({
    MY_CONST : 'some really important value'
}) {
    alert(MY_CONST);
}

在过去,我还创建了一个CONST名称空间,将所有常量放在其中。还有开销。天哪。

现在,我写var MY_CONST = 'whatever';吻。

忘记IE,使用const关键字。

const关键字在ECMAScript 6草案中,但到目前为止它只获得了少量的浏览器支持:http://kangax.github.io/compat-table/es6/。语法为:

const CONSTANT_NAME = 0;

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

/* 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