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

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


当前回答

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

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

其他回答

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

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

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

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

忘记IE,使用const关键字。

IE确实支持常量,比如:

<script language="VBScript">
 Const IE_CONST = True
</script>
<script type="text/javascript">
 if (typeof TEST_CONST == 'undefined') {
    const IE_CONST = false;
 }
 alert(IE_CONST);
</script>

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

但现在:

var myconst = value;

or

Object['myconst'] = value;

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

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

const name1 = value;

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