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

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


当前回答

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

const name1 = 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  

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

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

使用"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

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

JavaScript ES6(重新)引入了所有主流浏览器都支持的const关键字。

通过const声明的变量不能被重新声明或重新赋值。

除此之外,const的行为类似于let。

对于基本数据类型(Boolean, Null, Undefined, Number, String, Symbol),它的行为与预期一样:

const x = 1;
x = 2;
console.log(x); // 1 ...as expected, re-assigning fails

注意:注意关于对象的陷阱:

const o = {x: 1};
o = {x: 2};
console.log(o); // {x: 1} ...as expected, re-assigning fails

o.x = 2;
console.log(o); // {x: 2} !!! const does not make objects immutable!

const a = [];
a = [1];
console.log(a); // 1 ...as expected, re-assigning fails

a.push(1);
console.log(a); // [1] !!! const does not make objects immutable

如果你真的需要一个不可变且绝对恒定的对象:只需使用const ALL_CAPS来明确你的意图。无论如何,对于所有const声明来说,这都是一个很好的约定,所以只需依赖它即可。

不,不一般。Firefox实现了const,但我知道IE没有。


@John指出了const的一个常用命名实践,在其他语言中已经使用了很多年,我看不出为什么你不能使用它。当然,这并不意味着有人不会重写变量的值。:)