在JavaScript中有使用常量的方法吗?
如果不是,指定用作常量的变量的常见做法是什么?
在JavaScript中有使用常量的方法吗?
如果不是,指定用作常量的变量的常见做法是什么?
当前回答
在JavaScript中,我倾向于使用函数返回常量值。
function MY_CONSTANT() {
return "some-value";
}
alert(MY_CONSTANT());
其他回答
const关键字在ECMAScript 6草案中,但到目前为止它只获得了少量的浏览器支持:http://kangax.github.io/compat-table/es6/。语法为:
const CONSTANT_NAME = 0;
检查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
声明:我是这个工具的作者。
我在这方面也有问题。在花了很长一段时间寻找答案,看了大家的回答之后,我想我已经想出了一个可行的解决方案。
似乎我遇到的大多数答案都是使用函数来保存常量。正如许多论坛的用户所述,客户端用户可以很容易地重写这些函数。我对Keith evets的回答很感兴趣,他说常量对象不能被外部访问,只能从内部的函数访问。
所以我想出了这个解决方案:
把所有东西都放在一个匿名函数中,这样,变量、对象等就不能被客户端更改。也可以通过让其他函数从内部调用“真正的”函数来隐藏“真正的”函数。我还考虑过使用函数来检查客户端用户是否更改了函数。如果函数已经更改,请使用内部“受保护”且不能更改的变量将它们更改回来。
/*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代码的网站。
复制上面脚本中的所有代码,并将其粘贴到javascriptcompressor.com页面的顶部文本区域。 选中“Base62编码”复选框,选中“收缩变量”复选框。 按下压缩按钮。 粘贴并保存在.js文件中,并将其添加到页面头部。
我在Greasemonkey脚本中使用const而不是var,但这是因为它们只会在Firefox上运行… 名称约定也确实是可行的方法(我两者都做!)
显然,这表明需要一个标准化的跨浏览器const关键字。
但现在:
var myconst = value;
or
Object['myconst'] = value;
两者似乎都足够了,其他的就像用火箭筒打苍蝇一样。