你可以在 JavaScript 中使用常量变量吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2821509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:03:57  来源:igfitidea点击:

Can you use constant variables in JavaScript?

javascriptconstants

提问by chobo2

I read on one site that you can make constantvariables in JavaScript like:

我在一个网站上读到,您可以在 JavaScript 中创建常量变量,例如:

const x = 20;

but on another site I read that you can't. So I am confused now what is it now?

但在另一个网站上我读到你不能。所以我现在很困惑现在是什么?

Also in Visual Studio 2010 when I write constit underlines it in the JavaScript file and shows syntax error.

同样在 Visual Studio 2010 中,当我编写const它时,它会在 JavaScript 文件中加下划线并显示语法错误。

回答by J?rg W Mittag

constis a proposed feature of ECMAScript Harmony(together with a properly block-scoped letit is supposed to replace varand implicit globals). ECMAScript Harmony is a grab-bag of ideas for the next versions of ECMAScript.

const是 ECMAScript Harmony 的一项提议功能(连同适当的块范围,let它应该替换var和隐式全局变量)。ECMAScript Harmony 是 ECMAScript 下一个版本的创意集锦。

constwas also a part of ECMAScript 4.

const也是 ECMAScript 4 的一部分。

ECMAScript 4 was never released and never will be, and ECMAScript Harmony will only be released in a couple of years. Therefore, you cannot reliably use it.

ECMAScript 4 从未发布也永远不会发布,而 ECMAScript Harmony 将在几年后发布。因此,您无法可靠地使用它。

There are some implementations or derivatives of ECMAScript that implement const(ActionScript, for example). There are also some implementations that accept constas a synonym for var(IOW, you can use const, but it won't give you any protection.)

有一些 ECMAScript 的实现或派生实现const(例如 ActionScript)。还有一些实现接受const作为var(IOW,你可以使用const,但它不会给你任何保护。)

However, unless you absolutely can guarantee that your code will only run on very specific versions of very specific implementations of very specific derivatives of ECMAScript, it's probably better to avoid it. (Which is a real shame, because constand especially letare a hugeimprovement over varand implicit globals.)

但是,除非您绝对可以保证您的代码只会在 ECMAScript 的非常具体的衍生产品的非常具体的实现的非常具体的版本上运行,否则最好避免它。(这是一个真正的耻辱,因为const尤其let是对隐式全局变量的巨大改进var。)

回答by lincolnk

if you're looking for a read-only variable, you simulate that with something like

如果你正在寻找一个只读变量,你可以用类似的东西来模拟它

var constants = new (function() {
    var x = 20;
    this.getX = function() { return x; };
})();

and then use it like

然后像这样使用它

constants.getX()

回答by user2373071

The solution is to create an object and put all your constants in the object:

解决方案是创建一个对象并将所有常量放入该对象中:

const={};

const.x=20;

const.y=30;

Object.freeze(const);  // finally freeze the object

Usage:

用法:

var z=const.x + const.y;

Any attempt to modify the variable will generate an error:

任何修改变量的尝试都会产生一个错误:

const.x=100;  <== raises error

回答by le_m

JavaScript ES6 (re-)introduced the constkeywordwhich is supported in all major browsers.

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

Variables declared via constcannot be re-declared or re-assigned.

通过声明的变量const不能重新声明或重新分配。

Apart from that, constbehaves similar to let.

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

It behaves as expected for primitive datatypes (Boolean, Null, Undefined, Number, String, Symbol):

对于原始数据类型(Boolean、Null、Undefined、Number、String、Symbol),它的行为符合预期:

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

Attention:Be aware of the pitfalls regarding objects:

注意:请注意有关对象的陷阱:

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

回答by kennytm

There's no constin ECMAScript (disregarding the dead 4.0 version, and ActionScript).

constECMAScript 中没有(不考虑死的 4.0 版本和 ActionScript)。

The constis available in JScript.NET, and some recent versions of JS enginese.g. Firefox, Opera 9, Safari as a vendor-specific extension.

const是提供JScript.NET,和一些最近的JS引擎的版本如火狐,Opera 9中,Safari浏览器作为厂商专用的扩展。

回答by Samit

I believe there is something which is not with var , is a global variable....there is no const in js.

我相信有些东西不是 var ,是一个全局变量……js 中没有 const 。

var a="test"is different from a="test"

var a="test"不同于 a="test"

回答by Rajat

No, there is no data type "const" in JavaScript.

不,JavaScript 中没有数据类型“ const”。

JavaScript is a loosely typed language. Every kind of variable is declared with a var

JavaScript 是一种松散类型的语言。每种变量都用var声明

回答by rekordboy

Check out this doc, it outlines how to use const in javascript

查看此文档,它概述了如何在 javascript 中使用 const

http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml

http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml