[英]What's the proper way to implement constant variable?
ECMAScript 5 doesn't really support this. ECMAScript 5并不真正支持此功能。 There's a couple tricks you could use though.
不过,您可以使用一些技巧。
You could try something like this 你可以尝试这样的事情
var f = (function() {
var g = 5;
return function() {
return g;
};
})();
Now, every time you run f()
, you will also get 5
, and it's impossible to change the value of g
现在,每次运行
f()
,您也会得到5
,并且不可能更改g
的值
Another thing you could do is use Object.defineProperty 您可以做的另一件事是使用Object.defineProperty
var f = {};
Object.defineProperty(f, "g", {
configurable: false,
value: 5
});
f.g; // 5
Even if you try to change the property, fg
will stay set to 5
即使您尝试更改属性,
fg
仍将设置为5
f.g = 10;
f.g; // 5
If you're working with CommonJS style modules, you sort of get this functionality for "free". 如果您正在使用CommonJS样式模块,则可以“免费”获得此功能。 Again,
g
is non-configurable and always guaranteed to be 5. 同样,
g
是不可配置的,并且始终保证为5。
a.js a.js
var g = 5;
function foo() {
return g;
}
module.exports = foo;
b.js b.js
var a = require("./a");
a(); // 5
Quoting from the const
's MDN Docs , 引用
const
的MDN文档 ,
The current implementation of const is a Mozilla-specific extension and is not part of ECMAScript 5. It is supported in Firefox & Chrome (V8).
当前const的实现是Mozilla特定的扩展,不属于ECMAScript5。它在Firefox和Chrome(V8)中受支持。 As of Safari 5.1.7 and Opera 12.00, if you define a variable with const in these browsers, you can still change its value later.
从Safari 5.1.7和Opera 12.00开始,如果您在这些浏览器中使用const定义变量,则以后仍可以更改其值。 It is not supported in Internet Explorer 6-10, but is included in Internet Explorer 11. The const keyword currently declares the constant in the function scope (like variables declared with var).
它在Internet Explorer 6-10中不受支持,但在Internet Explorer 11中包含。const关键字当前在函数范围内声明常量(如用var声明的变量)。
Firefox, at least since version 13, throws a TypeError if you redeclare a constant.
Firefox(至少从版本13开始),如果您重新声明常量,则会引发TypeError。 None of the major browsers produce any notices or errors if you assign another value to a constant.
如果将另一个值分配给常量,则所有主流浏览器都不会产生任何通知或错误。 The return value of such an operation is that of the new value assigned, but the reassignment is unsuccessful only in Firefox and Chrome (at least since version 20).
此类操作的返回值是分配的新值的返回值,但是仅在Firefox和Chrome中(至少从版本20开始),重新分配才成功。
const is going to be defined by ECMAScript 6, but with different semantics.
const将由ECMAScript 6定义,但具有不同的语义。 Similar to variables declared with the let statement, constants declared with const will be block-scoped.
与用let语句声明的变量相似,用const声明的常量将是块作用域的。
const
is not part of ECMA Script 5, so it may not have to supported by all the environments and browsers. const
不是ECMA Script 5的一部分,因此不一定所有环境和浏览器都支持const
。
To have the similar behavior, you can see macek's answer . 要具有类似的行为,您可以查看macek的答案 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.