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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5786054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:50:31  来源:igfitidea点击:

How to declare string constants in JavaScript?

javascriptconstants

提问by Girish Chaudhari

I want to declare string constants in JavaScript.

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

Is there is a way to do that?

有没有办法做到这一点?

回答by alex

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

许多浏览器的实现(和 Node)都有常量,与const.

const SOME_VALUE = "Your string";

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

const意味着您不能将其重新分配给任何其他值。

Check the compatibility notesto see if your targeted browsers are supported.

检查兼容性说明以查看您的目标浏览器是否受支持。

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

或者,您也可以修改第一个示例,使用defineProperty()或它的朋友并创建writable属性false。这意味着变量的内容不能像常量一样被改变。

回答by Esteban Araya

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

JavaScript 中没有常量,但是要声明一个字面量,您要做的就是:

var myString = "Hello World";

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

我不确定将它们存储在资源文件中是什么意思;这不是 JavaScript 的概念。

回答by MattC

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)

你在使用 JQuery 吗?你想在多个 javascript 文件中使用常量吗?然后继续阅读。(这是我对相关 JQuery 问题的回答)

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:

有一个名为“getScript”的方便的 jQuery 方法。确保您使用的相对路径与从 html/jsp/etc 文件访问文件时使用的相对路径相同(即路径不是相对于您放置 getScript 方法的位置,而是相对于您的域路径)。例如,对于位于 localhost:8080/myDomain 的应用程序:

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

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

然后,如果你在一个名为 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

您现在可以打印出 'foofoo'

jsEnum.FOO

回答by Simon

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:

当然,当 OP 提交问题时,这不是一个选项,但是 ECMAScript 6 现在还允许通过“const”关键字使用常量:

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

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

You can see ECMAScript 6 adoption here.

您可以在此处查看 ECMAScript 6 的采用情况。

回答by Beckafly

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.

如果你在全局范围内这样做,这将是一个真正的常量,因为你不能覆盖 window 对象。

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

我创建了一个库来在 javascript 中创建常量和不可变对象。它仍然是 0.2 版,但它很好地完成了这个技巧。http://beckafly.github.io/insulatejs

回答by Mohit

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

内置 Object 的标准冻结功能可用于冻结包含常量的对象。

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

在严格模式下,在不可变对象上设置值会引发 TypeError。有关更多详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze

回答by Ryan Rho

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

从 ECMAScript 2015(又名 ES6)开始,您可以使用 const

const constantString = 'Hello';

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

但并非所有浏览器/服务器都支持这一点。为了支持这一点,请使用像 Babel 这样的 polyfill 库。

回答by Sandip Nirmal

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.

并使用defineObject write 函数将所有属性添加到该对象并为其赋值。

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

回答by Simon

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 Publicarea.

给这只猫剥皮的方法有很多。您可以在闭包中执行此操作。这段代码会给你一个只读的、命名空间的方式来拥有常量。只需在公共区域声明它们。

//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

回答by Rubi saini

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

您可以使用 Object 的 freeze 方法来创建一个常量。例如:

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

In this way you can not alter the configObj.

这样你就不能改变 configObj。