在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  

其他回答

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

const name1 = value;

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

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

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约定即可。

在JavaScript中,我倾向于使用函数返回常量值。

function MY_CONSTANT() {
   return "some-value";
}


alert(MY_CONSTANT());

如果你不介意使用函数:

var constant = function(val) {
   return function() {
        return val;
    }
}

这种方法为您提供函数而不是常规变量,但它保证一旦设置了值,就没有人可以更改值。

a = constant(10);

a(); // 10

b = constant(20);

b(); // 20

我个人觉得这相当令人愉快,特别是在我已经习惯了这种模式之后。

*除非有人在你调用函数常量之前重新定义了它

声明一个只读命名的常量。 通过const声明的变量不能被重新声明或重新赋值。 常量可以用大写或小写来声明,但通用的 惯例是全部使用大写字母。

// const c;
// c = 9;   //intialization and declearation at same place
const c = 9;
// const c = 9;// re-declare and initialization is not possible
console.log(c);//9