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

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


当前回答

使用"new"对象api,你可以这样做:

var obj = {};
Object.defineProperty(obj, 'CONSTANT', {
  configurable: false
  enumerable: true,
  writable: false,
  value: "your constant value"
});

请在Mozilla MDN上查看更多细节。它不是第一级变量,因为它是附加到对象上的,但如果你有一个作用域,你可以将它附加到那个对象上。这也可以。 例如,在全局作用域中这样做会在窗口上声明一个伪常量值(这是个坏主意,你不应该粗心地声明全局变量)

Object.defineProperty(this, 'constant', {
  enumerable: true, 
  writable: false, 
  value: 7, 
  configurable: false
});

> constant
=> 7
> constant = 5
=> 7

注意:赋值会在控制台中返回赋值,但变量的值不会改变

其他回答

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

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

伯克的答案的改进版本,让你做CONFIG。MY_CONST代替CONFIG.get('MY_CONST')。

它需要IE9+或真正的网络浏览器。

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

    var result = {};
    for (var n in constants)
        if (constants.hasOwnProperty(n))
            Object.defineProperty(result, n, { value: constants[n] });

    return result;
}());

*属性是只读的,只有初始值是不可变的。

好吧,这很难看,但它给了我一个在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测试。

ECMAScript 5引入了Object.defineProperty:

Object.defineProperty (window,'CONSTANT',{ value : 5, writable: false });

每个现代浏览器(以及IE≥9)都支持它。

参见:Object.defineProperty在ES5?

在Javascript中已经存在常量。你可以这样定义一个常数:

const name1 = value;

这不能通过重新分配来改变。