在线文档教程

const

const

常量是块范围的,就像使用let语句定义的变量一样。常量的值不能通过重新赋值而改变,并且不能重新声明。

语法

const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]];

nameN常量的名称,可以是任何合法的标识符。valueN常数值; 这可以是任何法律表达式,包括函数表达式。

描述

该声明创建一个常量,其作用域可以是全局的(在窗口对象上),也可以是声明它的块的本地。需要一个常量的初始值; 也就是说,您必须在声明它的同一个语句中指定它的值(这是有道理的,因为它以后不能更改)。

const创建了一个只读的参照值。它并不意味着其持有的价值是不变的,只是该变量标识符不能被重新分配。例如,在内容是对象的情况下,这意味着对象的内容(例如,其参数)可以被改变。

关于“时间死区”的所有事项适用于letconst

常量不能在同一范围内与函数或变量共享其名称。

示例

以下示例演示常量的行为。在浏览器控制台中试试这个。

// NOTE: Constants can be declared with uppercase or lowercase, but a common // convention is to use all-uppercase letters. // define MY_FAV as a constant and give it the value 7 const MY_FAV = 7; // this will throw an error MY_FAV = 20; // will print 7 console.log('my favorite number is: ' + MY_FAV // trying to redeclare a constant throws an error const MY_FAV = 20; // the name MY_FAV is reserved for constant above, so this will fail too var MY_FAV = 20; // this throws an error too let MY_FAV = 20; // it's important to note the nature of block scoping if (MY_FAV === 7) { // this is fine and creates a block scoped MY_FAV variable // (works equally well with let to declare a block scoped non const variable) let MY_FAV = 20; // MY_FAV is now 20 console.log('my favorite number is ' + MY_FAV // this gets hoisted into the global context and throws an error var MY_FAV = 20; } // MY_FAV is still 7 console.log('my favorite number is ' + MY_FAV // throws an error, missing initializer in const declaration const FOO; // const also works on objects const MY_OBJECT = {'key': 'value'}; // Attempting to overwrite the object throws an error MY_OBJECT = {'OTHER_KEY': 'value'}; // However, object keys are not protected, // so the following statement is executed without problem MY_OBJECT.key = 'otherValue'; // Use Object.freeze() to make object immutable // The same applies to arrays const MY_ARRAY = []; // It's possible to push items into the array MY_ARRAY.push('A' // ["A"] // However, assigning a new array to the variable throws an error MY_ARRAY = ['B'];

规范

SpecificationStatusComment
ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Let and Const Declarations' in that specification.StandardInitial definition.
ECMAScript Latest Draft (ECMA-262)The definition of 'Let and Const Declarations' in that specification.Living StandardNo changes.

浏览器兼容性

FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support21(Yes)36 (36)11125.1
Reassignment fails20(Yes)13 (13)11?10.0
Allowed in sloppy mode49.0?????

FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic supportNo support(Yes)(Yes)??(Yes)?(Yes)
Reassignment failsNo support(Yes)(Yes)??(Yes)10.0(Yes)
Allowed in sloppy modeNo support49.0?????49.0