在JavaScript中有使用常量的方法吗?
如果不是,指定用作常量的变量的常见做法是什么?
在JavaScript中有使用常量的方法吗?
如果不是,指定用作常量的变量的常见做法是什么?
当前回答
然而,没有确切的跨浏览器预定义的方法来做到这一点,你可以通过控制变量的范围来实现,如其他答案所示。
但是我建议使用名称空间来区别于其他变量。这将使与其他变量的碰撞概率降到最低。
正确的命名空间
var iw_constant={
name:'sudhanshu',
age:'23'
//all varibale come like this
}
使用时,它会是iw_constant。name或iw_constant。age
你也可以使用Object.freeze方法阻止添加任何新键或改变iw_constant中的任何键。但是它不支持传统浏览器。
ex:
Object.freeze(iw_constant);
对于较老的浏览器,可以使用polyfill进行冻结方法。
如果你可以调用函数下面是最好的跨浏览器方式定义常量。将对象限定在一个自执行函数中,并为常量返回一个get函数 例:
var iw_constant= (function(){
var allConstant={
name:'sudhanshu',
age:'23'
//all varibale come like this
};
return function(key){
allConstant[key];
}
};
//获取值use Iw_constant ('name')或Iw_constant ('age')
**在这两个例子中,你必须非常注意名称间距,这样你的对象或函数不会被其他库替换。(如果对象或函数本身将被替换,则整个常量将消失)
其他回答
在JavaScript中,我的实践是尽可能避免常量,而是使用字符串。当你想要向外界公开你的常量时,常量的问题就出现了:
例如,可以实现以下Date API:
date.add(5, MyModule.Date.DAY).add(12, MyModule.Date.HOUR)
但如果简单地写成:
date.add(5, "days").add(12, "hours")
这样,“天”和“小时”就像常数一样,因为你无法从外部改变“小时”代表的秒数。但是很容易覆盖MyModule.Date.HOUR。
这种方法还有助于调试。如果Firebug告诉你action === 18,你很难理解它的意思,但是当你看到action === "save"时,你马上就明白了。
"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。
我在Greasemonkey脚本中使用const而不是var,但这是因为它们只会在Firefox上运行… 名称约定也确实是可行的方法(我两者都做!)
不,不一般。Firefox实现了const,但我知道IE没有。
@John指出了const的一个常用命名实践,在其他语言中已经使用了很多年,我看不出为什么你不能使用它。当然,这并不意味着有人不会重写变量的值。:)
检查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
声明:我是这个工具的作者。