如何在 JavaScript 中声明字符串常量?

我想在 JavaScript 中声明字符串常量。

有办法吗?

151487 次浏览

Just declare variable outside of scope of any js function. Such variables will be global.

There's no constants in JavaScript, but to declare a literal all you have to do is:

var myString = "Hello World";

I'm not sure what you mean by store them in a resource file; that's not a JavaScript concept.

Many browsers' implementations (and Node) have constants, used with const.

const SOME_VALUE = "Your string";

This const means that you can't reassign it to any other value.

Check the compatibility notes to see if your targeted browsers are supported.

Alternatively, you could also modify the first example, using defineProperty() or its friends and make the writable property false. This will mean the variable's contents can not be changed, like a constant.

Are you using JQuery? Do you want to use the constants in multiple javascript files? Then read on. (This is my answer for a related JQuery question)

There is a handy jQuery method called 'getScript'. Make sure you use the same relative path that you would if accessing the file from your html/jsp/etc files (i.e. the path is NOT relative to where you place the getScript method, but instead relative to your domain path). For example, for an app at localhost:8080/myDomain:

$(document).ready(function() {
$.getScript('/myDomain/myScriptsDir/constants.js');
...

then, if you have this in a file called constants.js:

var jsEnum = { //not really an enum, just an object that serves a similar purpose
FOO : "foofoo",
BAR : "barbar",
}

You can now print out 'foofoo' with

jsEnum.FOO

Well, you can do it like so:

(function() {
var localByaka;
Object.defineProperty(window, 'Byaka', {
get: function() {
return localByaka;
},
set: function(val) {
localByaka = window.Byaka || val;
}
});
}());
window.Byaka = "foo"; //set constant
window.Byaka = "bar"; // try resetting it for shits and giggles
window.Byaka; // will allways return foo!

If you do this as above in global scope this will be a true constant, because you cannot overwrite the window object.

I've created a library to create constants and immutable objects in javascript. Its still version 0.2 but it does the trick nicely. http://beckafly.github.io/insulatejs

So many ways to skin this cat. You can do this in a closure. This code will give you a read-only , namespaced way to have constants. Just declare them in the Public area.

//Namespaced Constants
var MyAppName;
//MyAppName Namespace
(function (MyAppName) {
//MyAppName.Constants Namespace
(function (Constants) {
//Private
function createConstant(name, val) {
Object.defineProperty(MyAppName.Constants, name, {
value: val,
writable: false
});
}


//Public
Constants.FOO = createConstant("FOO", 1);
Constants.FOO2 = createConstant("FOO2", 1);


MyAppName.Constants = Constants;
})(MyAppName.Constants || (MyAppName.Constants = {}));
})(MyAppName || (MyAppName = {}));

Usage:

console.log(MyAppName.Constants.FOO);       //prints 1
MyAppName.Constants.FOO = 2;
console.log(MyAppName.Constants.FOO);       //does not change - still prints 1

Standard freeze function of built-in Object can be used to freeze an object containing constants.

var obj = {
constant_1 : 'value_1'
};
Object.freeze(obj);
obj.constant_1 = 'value_2';   //Silently does nothing
obj.constant_2 = 'value_3';   //Silently does nothing

In strict mode, setting values on immutable object throws TypeError. For more details, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze

Of course, this wasn't an option when the OP submitted the question, but ECMAScript 6 now also allows for constants by way of the "const" keyword:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

You can see ECMAScript 6 adoption here.

You can use freeze method of Object to create a constant. For example:

var configObj ={timeOut :36000};
Object.freeze(configObj);

In this way you can not alter the configObj.

Starting ECMAScript 2015 (a.k.a ES6), you can use const

const constantString = 'Hello';

But not all browsers/servers support this yet. In order to support this, use a polyfill library like Babel.

Use global namespace or global object like Constants.

var Constants = {};

And using defineObject write function which will add all properties to that object and assign value to it.

function createConstant (prop, value) {
Object.defineProperty(Constants , prop, {
value: value,
writable: false
});
};