Javascript -- Convert String to Constant
How to convert a string to constant in Javascript
e.g
开发者_运维百科str = "User" //Javascript magic User
You don't -- JavaScript does not have constants, nor readonly variables. (Some extensions to JavaScript provide for read-only accessors, but that's something else entirely.)
As far as I know there is no such thing as constants in Javascript. But you could create an object that will expose this information as read-only properties:
<script type="text/javascript">
function defineConstant(obj, name, value) {
// Non-standard!
if(obj.__defineGetter__) {
obj.__defineGetter__(name, function () { return value; });
obj.__defineSetter__(name, function() { throw "Read-only property"; });
} else {
if(typeof(Object.defineProperty) != 'undefined') {
try {
// First, trying the "normal" way
defineReadOnlyProperty(obj, name, value);
} catch(ex) {
var temp = obj;
// Ugly hack to make "defineProperty" work in IE
// (only works on DOM elements prior IE9)
obj = document.createElement('DIV');
// Copying object members
for(var key in temp)
obj[key] = temp[key];
// Now it should define property
defineReadOnlyProperty(obj, name, value);
}
}
}
return obj;
}
function defineReadOnlyProperty(obj, name, value) {
Object.defineProperty(obj, name, {
get: function() { return value; },
set: function() { throw "Read-only property"; }
});
}
</script>
And the usage of above function will look like:
<script type="text/javascript">
var Global = {};
Global = defineConstant(Global, 'MagicUser', 'User');
// Getting "User"
alert(Global.MagicUser);
// Throws an error
Global.MagicUser = 'User2';
</script>
Hope this will help you.
精彩评论