/* author Keith Evetts 2009 License: LGPLanonymous 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 generatedthey 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 VATtry{SETCONST( 'VAT', 0.22 );} catch ( exc ) {alert (exc.message);}//check old value of VAT remainsalert( CONST('VAT') );
// try to get at constants object directlyconstants['DODO'] = "dead bird"; // error
// define MY_FAV as a constant and give it the value 7const MY_FAV = 7;
// this will throw an error - Uncaught TypeError: Assignment to constant variable.MY_FAV = 20;
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 silentlyalert('err1 '+err1);}alert('const '+FOO);if(FOO=='?NO!'){// changed in Sf/Op - set back to original valueFOO=original;}}catch(err2){// IE failalert('err2 '+err2);// set var (no var keyword - Chrome/Firefox complain about redefining const)FOO='{0}';alert('var '+FOO);}alert('FOO '+FOO);
/*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 textof the error messages.*/
//object literal to hold the constantsvar 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 hasto 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'tsee any of your coding call this function. You call the _makeDef() in your code and that function callsthis 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 thisfunction. The argument 't' is the name of the const and doesn't need to be all caps because I set itto upper case within the function, 'y' is the value of the value of the const and has to exist. Imake 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. Theargument 's' is the name of the const and doesn't need to be all capse because I set it to upper casewithin the function. I make a different variable to make it harder for a user to figure out whats goingon. The function returns the _access function call. I pass the new variable and the original stringalong to the _access function. I do this because if a user is trying to get the value of something, ifthere is an error the argument doesn't get displayed with upper case in the error message. You call thisfunction 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 throughthis function. The argument 'g' is the name of the const and its all upper case, 'f' is also the nameof the const, but its the original string that was passed to the _getDef() function. If there is anerror, the original string, 'f', is displayed. This makes it harder for a user to figure out how theconstants are being stored. If there is a property with the same name in the object holder, we returnthe constant value. If not, we check if the 'f' variable exists, if not, set it to the value of 'g' andthrow an error. This is a 'hidden' function and the user doesn't see any of your coding call thisfunction. 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 thefunctions inside this anonymous function. These variables are strings of the four above functions andwill be used by the all-dreaded eval() function to set them back to their original if any of them shouldbe 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 willcheck if a specific line of code is inside a given function. If it is, then we do nothing, if not, thenwe use the eval() function to set the function back to its original coding using the function stringvariables above. This function will also throw an error depending upon the doError variable being set to trueThis is a 'hidden' function and the user doesn't see any of your coding call this function. You call thedoCodeCheck() function and that function calls this function. - You can change the error messages towhatever 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 differentvariable to make it harder for a user to figure out whats going on. You call this function in your code to checkif any of the functions has been changed by the user.*/self._doCodeCheck = function(v) {l = v;_doFunctionCheck(l);};}())
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;}());
var ConstJs = require('constjs');
var Colors = ConstJs.enum("blue red");
var myColor = Colors.blue;
console.log(myColor.isBlue()); // output trueconsole.log(myColor.is('blue')); // output trueconsole.log(myColor.is('BLUE')); // output trueconsole.log(myColor.is(0)); // output trueconsole.log(myColor.is(Colors.blue)); // output true
console.log(myColor.isRed()); // output falseconsole.log(myColor.is('red')); // output false
console.log(myColor._id); // output blueconsole.log(myColor.name()); // output blueconsole.log(myColor.toString()); // output blue
// See how CamelCase is used to generate the isXxx() functionsvar AppMode = ConstJs.enum('SIGN_UP, LOG_IN, FORGOT_PASSWORD');var curMode = AppMode.LOG_IN;
console.log(curMode.isLogIn()); // output trueconsole.log(curMode.isSignUp()); // output falseconsole.log(curMode.isForgotPassword()); // output false
创建字符串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 trueconsole.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
// const c;// c = 9; //intialization and declearation at same placeconst c = 9;// const c = 9;// re-declare and initialization is not possibleconsole.log(c);//9