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

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


当前回答

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声明来说,这都是一个很好的约定,所以只需依赖它即可。

其他回答

另一种选择是:

var constants = {
      MY_CONSTANT : "myconstant",
      SOMETHING_ELSE : 123
    }
  , constantMap = new function ConstantMap() {};

for(var c in constants) {
  !function(cKey) {
    Object.defineProperty(constantMap, cKey, {
      enumerable : true,
      get : function(name) { return constants[cKey]; }
    })
  }(c);
}

然后简单地:var foo = constantMap。MY_CONSTANT

如果你使用constantMap。MY_CONSTANT = "bar"它不会有任何影响,因为我们试图使用赋值操作符和getter,因此使用constantMap。MY_CONSTANT === "myconstant"仍然为真。

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

const name1 = value;

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

如果你不介意使用函数:

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

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

a = constant(10);

a(); // 10

b = constant(20);

b(); // 20

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

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

"use strict";

var constants = Object.freeze({
    "π": 3.141592653589793 ,
    "e": 2.718281828459045 ,
    "i": Math.sqrt(-1)
});

constants.π;        // -> 3.141592653589793
constants.π = 3;    // -> TypeError: Cannot assign to read only property 'π' …
constants.π;        // -> 3.141592653589793

delete constants.π; // -> TypeError: Unable to delete property.
constants.π;        // -> 3.141592653589793

看到Object.freeze。如果想让常量引用只读,也可以使用const。

关键字“const”早前就被提出了,现在它已经被正式包含在ES6中。通过使用const关键字,可以传递一个作为不可变字符串的值/字符串。