在JavaScript中有使用常量的方法吗?
如果不是,指定用作常量的变量的常见做法是什么?
在JavaScript中有使用常量的方法吗?
如果不是,指定用作常量的变量的常见做法是什么?
当前回答
IE确实支持常量,比如:
<script language="VBScript">
Const IE_CONST = True
</script>
<script type="text/javascript">
if (typeof TEST_CONST == 'undefined') {
const IE_CONST = false;
}
alert(IE_CONST);
</script>
其他回答
IE确实支持常量,比如:
<script language="VBScript">
Const IE_CONST = True
</script>
<script type="text/javascript">
if (typeof TEST_CONST == 'undefined') {
const IE_CONST = false;
}
alert(IE_CONST);
</script>
检查https://www.npmjs.com/package/constjs,它提供了三个函数来创建枚举、字符串const和位图。返回的结果要么是冻结的,要么是密封的,因此你不能在属性创建后更改/删除,你也不能向返回的结果添加新的属性
创建枚举:
var ConstJs = require('constjs');
var Colors = ConstJs.enum("blue red");
var myColor = Colors.blue;
console.log(myColor.isBlue()); // output true
console.log(myColor.is('blue')); // output true
console.log(myColor.is('BLUE')); // output true
console.log(myColor.is(0)); // output true
console.log(myColor.is(Colors.blue)); // output true
console.log(myColor.isRed()); // output false
console.log(myColor.is('red')); // output false
console.log(myColor._id); // output blue
console.log(myColor.name()); // output blue
console.log(myColor.toString()); // output blue
// See how CamelCase is used to generate the isXxx() functions
var AppMode = ConstJs.enum('SIGN_UP, LOG_IN, FORGOT_PASSWORD');
var curMode = AppMode.LOG_IN;
console.log(curMode.isLogIn()); // output true
console.log(curMode.isSignUp()); // output false
console.log(curMode.isForgotPassword()); // output false
创建String const:
var ConstJs = require('constjs');
var Weekdays = ConstJs.const("Mon, Tue, Wed");
console.log(Weekdays); // output {Mon: 'Mon', Tue: 'Tue', Wed: 'Wed'}
var today = Weekdays.Wed;
console.log(today); // output: 'Wed';
创建位图:
var ConstJs = require('constjs');
var ColorFlags = ConstJs.bitmap("blue red");
console.log(ColorFlags.blue); // output false
var StyleFlags = ConstJs.bitmap(true, "rustic model minimalist");
console.log(StyleFlags.rustic); // output true
var CityFlags = ConstJs.bitmap({Chengdu: true, Sydney: false});
console.log(CityFlags.Chengdu); //output true
console.log(CityFlags.Sydney); // output false
var DayFlags = ConstJs.bitmap(true, {Mon: false, Tue: true});
console.log(DayFlags.Mon); // output false. Default val wont override specified val if the type is boolean
欲了解更多信息,请结帐
https://www.npmjs.com/package/constjs 或https://github.com/greenlaw110/constjs
声明:我是这个工具的作者。
显然,这表明需要一个标准化的跨浏览器const关键字。
但现在:
var myconst = value;
or
Object['myconst'] = value;
两者似乎都足够了,其他的就像用火箭筒打苍蝇一样。
不,不一般。Firefox实现了const,但我知道IE没有。
@John指出了const的一个常用命名实践,在其他语言中已经使用了很多年,我看不出为什么你不能使用它。当然,这并不意味着有人不会重写变量的值。:)
从ES2015开始,JavaScript有了const的概念:
const MY_CONSTANT = "some-value";
这将工作在几乎所有的浏览器除了ie8, 9和10。有些可能还需要启用严格模式。
如果你需要支持旧的浏览器或使用遗留代码,你可以使用var和像ALL_CAPS这样的约定来表明某些值不应该被修改:
var MY_CONSTANT = "some-value";