Are there constants in JavaScript?
有没有在javascript中使用常量的方法?
如果没有,指定用作常量的变量的常见做法是什么?
自ES2015以来,javascript的概念是
1 | const MY_CONSTANT ="some-value"; |
除了IE 8、9和10之外,这在几乎所有的浏览器中都可以使用。有些可能还需要启用严格模式。
如果需要支持旧浏览器或使用旧代码,可以使用
1 | var MY_CONSTANT ="some-value"; |
您是否试图保护变量不被修改?如果是,则可以使用模块模式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | var CONFIG = (function() { var private = { 'MY_CONST': '1', 'ANOTHER_CONST': '2' }; return { get: function(name) { return private[name]; } }; })(); alert('MY_CONST: ' + CONFIG.get('MY_CONST')); // 1 CONFIG.MY_CONST = '2'; alert('MY_CONST: ' + CONFIG.get('MY_CONST')); // 1 CONFIG.private.MY_CONST = '2'; // error alert('MY_CONST: ' + CONFIG.get('MY_CONST')); // 1 |
使用此方法,无法修改值。但是,必须在config()上使用get()方法。
如果不需要严格保护变量值,那么只需按照建议进行操作,并使用所有上限的约定。
ecmascript 6草案中有
1 | const CONSTANT_NAME = 0; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | "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。如果要使
IE支持常量,比如:
1 2 3 4 5 6 7 8 | <script language="VBScript"> Const IE_CONST = True <script type="text/javascript"> if (typeof TEST_CONST == 'undefined') { const IE_CONST = false; } alert(IE_CONST); |
ecmascript 5引入了
1 | Object.defineProperty (window,'CONSTANT',{ value : 5, writable: false }); |
每个现代浏览器都支持它(以及IE≥9)。
另请参见:ES5中的object.defineproperty?
不,不是一般情况。火狐实现了
@约翰指出了一种常见的常量命名方法,这种方法已经在其他语言中使用了多年,我看不出你为什么不能使用它。当然,这并不意味着任何人都不会重写变量的值。:)
Mozilla MDN Web文档包含关于
1 2 3 4 5 | // define MY_FAV as a constant and give it the value 7 const MY_FAV = 7; // this will throw an error - Uncaught TypeError: Assignment to constant variable. MY_FAV = 20; |
但遗憾的是,IE9/10仍然不支持
So, what is IE9 doing with const? So
far, our decision has been to not
support it. It isn’t yet a consensus
feature as it has never been available
on all browsers....
In the end, it seems like the best
long term solution for the web is to
leave it out and to wait for
standardization processes to run their
course.
他们没有实现它,因为其他浏览器没有正确地实现它?!太害怕做得更好?无论标准定义与否,常量都是常量:设置一次,永不更改。
对于所有的想法:每个函数都可以被覆盖(XSS等)。因此,
更新:IE11支持
IE11 includes support for the well-defined and commonly used features of the emerging ECMAScript 6 standard including let,
const ,Map ,Set , andWeakMap , as well as__proto__ for improved interoperability.
在JavaScript中,我的首选是使用函数返回常量值。
1 2 3 4 5 6 | function MY_CONSTANT() { return"some-value"; } alert(MY_CONSTANT()); |
使用"new"对象API,您可以这样做:
1 2 3 4 5 6 7 | var obj = {}; Object.defineProperty(obj, 'CONSTANT', { configurable: false enumerable: true, writable: false, value:"your constant value" }); |
在MozillaMDN上查看这个,了解更多细节。它不是第一级变量,因为它附加到一个对象上,但是如果你有一个作用域,任何东西,你都可以附加到它上。
1 2 3 4 5 6 7 8 9 10 11 | Object.defineProperty(this, 'constant', { enumerable: true, writable: false, value: 7, configurable: false }); > constant => 7 > constant = 5 => 7 |
注意:赋值将在控制台中返回赋值,但变量的值不会更改。
如果您不介意使用函数:
1 2 3 4 5 | var constant = function(val) { return function() { return val; } } |
这种方法为您提供函数而不是常规变量,但它保证*一旦设置了值,就没有人可以更改它。
1 2 3 4 5 6 7 | a = constant(10); a(); // 10 b = constant(20); b(); // 20 |
我个人觉得这相当令人愉快,特别是在我习惯了这种从淘汰的观察器模式之后。
除非有人在调用函数之前重新定义了该函数
尽可能将常量分组到结构中:
例如,在我当前的游戏项目中,我使用了以下内容:
1 2 3 4 5 6 | var CONST_WILD_TYPES = { REGULAR: 'REGULAR', EXPANDING: 'EXPANDING', STICKY: 'STICKY', SHIFTING: 'SHIFTING' }; |
任务:
1 | var wildType = CONST_WILD_TYPES.REGULAR; |
比较:
1 2 3 | if (wildType === CONST_WILD_TYPES.REGULAR) { // do something here } |
最近我正在使用,用于比较:
1 2 3 4 5 6 7 8 | switch (wildType) { case CONST_WILD_TYPES.REGULAR: // do something here break; case CONST_WILD_TYPES.EXPANDING: // do something here break; } |
IE11采用了新的ES6标准,具有"const"声明。上述功能适用于早期的浏览器,如IE8、IE9和IE10。
您可以很容易地为脚本配备一种可设置但不可更改的常量机制。尝试更改它们将产生错误。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | /* author Keith Evetts 2009 License: LGPL anonymous function sets up: global function SETCONST (String name, mixed value) global function CONST (String name) constants once set may not be altered - console error is generated they are retrieved as CONST(name) the object holding the constants is private and cannot be accessed from the outer script directly, only through the setter and getter provided */ (function(){ var constants = {}; self.SETCONST = function(name,value) { if (typeof name !== 'string') { throw new Error('constant name is not a string'); } if (!value) { throw new Error(' no value supplied for constant ' + name); } else if ((name in constants) ) { throw new Error('constant ' + name + ' is already defined'); } else { constants[name] = value; return true; } }; self.CONST = function(name) { if (typeof name !== 'string') { throw new Error('constant name is not a string'); } if ( name in constants ) { return constants[name]; } else { throw new Error('constant ' + name + ' has not been defined'); } }; }()) // ------------- demo ---------------------------- SETCONST( 'VAT', 0.175 ); alert( CONST('VAT') ); //try to alter the value of VAT try{ SETCONST( 'VAT', 0.22 ); } catch ( exc ) { alert (exc.message); } //check old value of VAT remains alert( CONST('VAT') ); // try to get at constants object directly constants['DODO'] ="dead bird"; // error |
忘记ie,使用
然而,没有确切的跨浏览器预定义方法来实现这一点,您可以通过控制变量的范围来实现,如其他答案所示。
但我建议使用名称空间来区分其他变量。这将把碰撞的可能性从其他变量减少到最小。
适当的名称间距,如
1 2 3 4 5 | var iw_constant={ name:'sudhanshu', age:'23' //all varibale come like this } |
因此,在使用时,它将是
您还可以使用object.freeze方法阻止添加任何新键或更改IW_常量内的任何键。但是,传统浏览器不支持它。
前任:
1 | Object.freeze(iw_constant); |
对于较旧的浏览器,可以使用polyfill进行冻结方法。
如果您可以调用函数,那么下面是定义常量的最佳跨浏览器方法。在自执行函数中确定对象范围,并返回常量的get函数前任:
1 2 3 4 5 6 7 8 9 10 11 12 | var iw_constant= (function(){ var allConstant={ name:'sudhanshu', age:'23' //all varibale come like this }; return function(key){ allConstant[key]; } }; |
//要获取值,请使用
**在这两个示例中,您必须非常小心名称间距,这样就不应该通过其他库替换对象或函数。(如果对象或函数本身将被替换,则整个常量将消失)
有一段时间,我在传递给
1 2 3 4 5 | with ({ MY_CONST : 'some really important value' }) { alert(MY_CONST); } |
在过去,我还创建了一个
现在,我只做了一个接吻。
我的意见(仅适用于对象)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | var constants = (function(){ var a = 9; //GLOBAL CONSTANT (through"return") window.__defineGetter__("GCONST", function(){ return a; }); //LOCAL CONSTANT return { get CONST(){ return a; } } })(); constants.CONST = 8; //9 alert(constants.CONST); //9 |
尝试!但是理解——这是对象,但不是简单的变量。
也尝试一下:
1 | const a = 9; |
I too have had a problem with this. And after quite a while searching for the answer and looking at all the responses by everybody, I think I've come up with a viable solution to this.
It seems that most of the answers that I've come across is using functions to hold the constants. As many of the users of the MANY forums post about, the functions can be easily over written by users on the client side. I was intrigued by Keith Evetts' answer that the constants object can not be accessed by the outside, but only from the functions on the inside.
So I came up with this solution:
Put everything inside an anonymous function so that way, the variables, objects, etc. cannot be changed by the client side. Also hide the 'real' functions by having other functions call the 'real' functions from the inside. I also thought of using functions to check if a function has been changed by a user on the client side. If the functions have been changed, change them back using variables that are 'protected' on the inside and cannot be changed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | /*Tested in: IE 9.0.8; Firefox 14.0.1; Chrome 20.0.1180.60 m; Not Tested in Safari*/ (function(){ /*The two functions _define and _access are from Keith Evetts 2009 License: LGPL (SETCONST and CONST). They're the same just as he did them, the only things I changed are the variable names and the text of the error messages. */ //object literal to hold the constants var j = {}; /*Global function _define(String h, mixed m). I named it define to mimic the way PHP 'defines' constants. The argument 'h' is the name of the const and has to be a string, 'm' is the value of the const and has to exist. If there is already a property with the same name in the object holder, then we throw an error. If not, we add the property and set the value to it. This is a 'hidden' function and the user doesn't see any of your coding call this function. You call the _makeDef() in your code and that function calls this function. - You can change the error messages to whatever you want them to say. */ self._define = function(h,m) { if (typeof h !== 'string') { throw new Error('I don\'t know what to do.'); } if (!m) { throw new Error('I don\'t know what to do.'); } else if ((h in j) ) { throw new Error('We have a problem!'); } else { j[h] = m; return true; } }; /*Global function _makeDef(String t, mixed y). I named it makeDef because we 'make the define' with this function. The argument 't' is the name of the const and doesn't need to be all caps because I set it to upper case within the function, 'y' is the value of the value of the const and has to exist. I make different variables to make it harder for a user to figure out whats going on. We then call the _define function with the two new variables. You call this function in your code to set the constant. You can change the error message to whatever you want it to say. */ self._makeDef = function(t, y) { if(!y) { throw new Error('I don\'t know what to do.'); return false; } q = t.toUpperCase(); w = y; _define(q, w); }; /*Global function _getDef(String s). I named it getDef because we 'get the define' with this function. The argument 's' is the name of the const and doesn't need to be all capse because I set it to upper case within the function. I make a different variable to make it harder for a user to figure out whats going on. The function returns the _access function call. I pass the new variable and the original string along to the _access function. I do this because if a user is trying to get the value of something, if there is an error the argument doesn't get displayed with upper case in the error message. You call this function in your code to get the constant. */ self._getDef = function(s) { z = s.toUpperCase(); return _access(z, s); }; /*Global function _access(String g, String f). I named it access because we 'access' the constant through this function. The argument 'g' is the name of the const and its all upper case, 'f' is also the name of the const, but its the original string that was passed to the _getDef() function. If there is an error, the original string, 'f', is displayed. This makes it harder for a user to figure out how the constants are being stored. If there is a property with the same name in the object holder, we return the constant value. If not, we check if the 'f' variable exists, if not, set it to the value of 'g' and throw an error. This is a 'hidden' function and the user doesn't see any of your coding call this function. You call the _getDef() function in your code and that function calls this function. You can change the error messages to whatever you want them to say. */ self._access = function(g, f) { if (typeof g !== 'string') { throw new Error('I don\'t know what to do.'); } if ( g in j ) { return j[g]; } else { if(!f) { f = g; } throw new Error('I don\'t know what to do. I have no idea what \''+f+'\' is.'); } }; /*The four variables below are private and cannot be accessed from the outside script except for the functions inside this anonymous function. These variables are strings of the four above functions and will be used by the all-dreaded eval() function to set them back to their original if any of them should be changed by a user trying to hack your code. */ var _define_func_string ="function(h,m) {"+" if (typeof h !== 'string') { throw new Error('I don\'t know what to do.'); }"+" if (!m) { throw new Error('I don\'t know what to do.'); }"+" else if ((h in j) ) { throw new Error('We have a problem!'); }"+" else {"+" j[h] = m;"+" return true;"+" }"+" }"; var _makeDef_func_string ="function(t, y) {"+" if(!y) { throw new Error('I don\'t know what to do.'); return false; }"+" q = t.toUpperCase();"+" w = y;"+" _define(q, w);"+" }"; var _getDef_func_string ="function(s) {"+" z = s.toUpperCase();"+" return _access(z, s);"+" }"; var _access_func_string ="function(g, f) {"+" if (typeof g !== 'string') { throw new Error('I don\'t know what to do.'); }"+" if ( g in j ) { return j[g]; }"+" else { if(!f) { f = g; } throw new Error('I don\'t know what to do. I have no idea what \''+f+'\' is.'); }"+" }"; /*Global function _doFunctionCheck(String u). I named it doFunctionCheck because we're 'checking the functions' The argument 'u' is the name of any of the four above function names you want to check. This function will check if a specific line of code is inside a given function. If it is, then we do nothing, if not, then we use the eval() function to set the function back to its original coding using the function string variables above. This function will also throw an error depending upon the doError variable being set to true This is a 'hidden' function and the user doesn't see any of your coding call this function. You call the doCodeCheck() function and that function calls this function. - You can change the error messages to whatever you want them to say. */ self._doFunctionCheck = function(u) { var errMsg = 'We have a BIG problem! You\'ve changed my code.'; var doError = true; d = u; switch(d.toLowerCase()) { case"_getdef": if(_getDef.toString().indexOf("z = s.toUpperCase();") != -1) { /*do nothing*/ } else { eval("_getDef ="+_getDef_func_string); if(doError === true) { throw new Error(errMsg); } } break; case"_makedef": if(_makeDef.toString().indexOf("q = t.toUpperCase();") != -1) { /*do nothing*/ } else { eval("_makeDef ="+_makeDef_func_string); if(doError === true) { throw new Error(errMsg); } } break; case"_define": if(_define.toString().indexOf("else if((h in j) ) {") != -1) { /*do nothing*/ } else { eval("_define ="+_define_func_string); if(doError === true) { throw new Error(errMsg); } } break; case"_access": if(_access.toString().indexOf("else { if(!f) { f = g; }") != -1) { /*do nothing*/ } else { eval("_access ="+_access_func_string); if(doError === true) { throw new Error(errMsg); } } break; default: if(doError === true) { throw new Error('I don\'t know what to do.'); } } }; /*Global function _doCodeCheck(String v). I named it doCodeCheck because we're 'doing a code check'. The argument 'v' is the name of one of the first four functions in this script that you want to check. I make a different variable to make it harder for a user to figure out whats going on. You call this function in your code to check if any of the functions has been changed by the user. */ self._doCodeCheck = function(v) { l = v; _doFunctionCheck(l); }; }()) |
似乎安全性确实是一个问题,并且没有办法从客户端"隐藏"您的编程。我的一个好主意是压缩您的代码,这样任何人,包括您,程序员,都很难阅读和理解它。有一个站点可以访问:http://javascriptcompressor.com/。(这不是我的网站,别担心我没有做广告。)这是一个可以让你免费压缩和混淆javascript代码的网站。
显然,这表明需要一个标准化的跨浏览器常量关键字。
但现在:
1 | var myconst = value; |
或
1 | Object['myconst'] = value; |
这两个看起来都足够了,其他的都像是用火箭筒射杀一只苍蝇。
在JavaScript中,我的实践是尽可能避免常量,而是使用字符串。当您想将常量暴露于外部世界时,会出现常量问题:
例如,可以实现以下日期API:
1 | date.add(5, MyModule.Date.DAY).add(12, MyModule.Date.HOUR) |
但简单地写:
1 | date.add(5,"days").add(12,"hours") |
这样,"天"和"小时"就真的像常量,因为你不能从外部改变"小时"代表多少秒。但很容易覆盖
这种方法也有助于调试。如果Firebug告诉你
javascriptES6(re-)引入了所有主要浏览器都支持的
Variables declared via
const cannot be re-declared or re-assigned.
除此之外,
对于基本数据类型(布尔、空、未定义、数字、字符串、符号),它的行为与预期一致:
1 2 3 | const x = 1; x = 2; console.log(x); // 1 ...as expected, re-assigning fails |
注意:注意物体的缺陷:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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 |
如果你真的需要一个不变的、绝对不变的对象:只需使用
我在我的greasemonkey脚本中使用
如果值得一提的话,可以使用
1 | angularApp.constant('YOUR_CONSTANT', 'value'); |
一个改进版的伯克的答案,可以让你做
它需要IE9+或真正的Web浏览器。
1 2 3 4 5 6 7 8 9 10 11 12 13 | var CONFIG = (function() { var constants = { 'MY_CONST': 1, 'ANOTHER_CONST': 2 }; var result = {}; for (var n in constants) if (constants.hasOwnProperty(n)) Object.defineProperty(result, n, { value: constants[n] }); return result; }()); |
>只有在初始值不可变的情况下,属性才是只读的。
好吧,这很难看,但它在火狐和Chromium中给了我一个常量,一个常量(wtf?)在游猎和歌剧中,以及在IE中的变量。
当然eval()是邪恶的,但是没有它,IE就会抛出一个错误,阻止脚本运行。
Safari和Opera支持const关键字,但您可以更改const的值。
在本例中,服务器端代码正在将javascript写入页面,并将0替换为一个值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | try{ // i can haz const? eval("const FOO='{0}';"); // for reals? var original=FOO; try{ FOO='?NO!'; }catch(err1){ // no err from Firefox/Chrome - fails silently alert('err1 '+err1); } alert('const '+FOO); if(FOO=='?NO!'){ // changed in Sf/Op - set back to original value FOO=original; } }catch(err2){ // IE fail alert('err2 '+err2); // set var (no var keyword - Chrome/Firefox complain about redefining const) FOO='{0}'; alert('var '+FOO); } alert('FOO '+FOO); |
这对什么有好处?不多,因为它不是跨浏览器。充其量,至少有些浏览器不会让书签或第三方脚本修改这个值,这也许是一种小小的平静。
使用Firefox 2、3、3.6、4、Iron 8、Chrome 10、12、Opera 11、Safari 5、IE 6、9进行测试。
在javascript中已经存在常量。您可以这样定义常量:
1 | const name1 = value; |
这无法通过重新分配进行更改。
关键字"const"是早先提出的,现在它已正式包含在es6中。通过使用const关键字,可以传递将作为不可变字符串的值/字符串。
另一种选择是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | var constants = { MY_CONSTANT :"myconstant", SOMETHING_ELSE : 123 } , constantMap = new function ConstantMap() {}; for(var c in constants) { !function(cKey) { Object.defineProperty(constantMap, cKey, { enumerable : true, get : function(name) { return constants[cKey]; } }) }(c); } |
然后简单地说:
如果您使用
const关键字在jawscript语言中可用,但不支持IE浏览器。支持所有浏览器。
除上述内容外,
在javascript中引入常量充其量是一种黑客行为。
在javascript中实现持久的和全局可访问的值的一个好方法是使用一些"只读"属性声明一个对象文本,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | my={get constant1(){return"constant 1 <hr><P>签出https://www.npmjs.com/package/constjs,它提供三个函数来创建枚举、字符串const和位图。返回的结果被冻结或密封,因此在创建属性后不能更改/删除这些属性,也不能向返回的结果添加新属性。</P><P>创建枚举:</P>[cc lang="javascript"]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 |
创建字符串常量:
1 2 3 4 5 6 7 | 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'; |
创建位图:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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
免责声明:如果这个工具是我的作者。
Declare a readonly named constatnt.
Variables declared via const cannot be re-declared or re-assigned.
Constants can be declared with uppercase or lowercase, but a common
convention is to use all-uppercase letters.
1 2 3 4 5 | // const c; // c = 9; //intialization and declearation at same place const c = 9; // const c = 9;// re-declare and initialization is not possible console.log(c);//9 |