可以在 JavaScript 中声明全局常量吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4174552/
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 11:15:01  来源:igfitidea点击:

Can global constants be declared in JavaScript?

javascriptvariablesconstantsglobal-variables

提问by Giffyguy

If so, what is the syntax for such a declaration?

如果是这样,这种声明的语法是什么?

采纳答案by Pointy

Javascript doesn't really have the notion of a named constant, or an immutable property of an object. (Note that I'm not talking about ES5 here.)

Javascript 并没有真正的命名常量或对象的不可变属性的概念。(请注意,我在这里不是在谈论 ES5。)

You can declare globals with a simple vardeclaration in the global scope, like outside any function in a script included by a web page:

您可以var在全局范围内使用简单的声明来声明全局变量,就像在网页包含的脚本中的任何函数之外一样:

<script>
  var EXACTLY_ONE = 1;

Then your code can use that constant of course, though it's not really "constant" because the value can be changed (the property updated, in other words).

然后您的代码当然可以使用该常量,尽管它不是真正的“常量”,因为该值可以更改(换句话说,属性已更新)。

edit— this is an ancient answer to an ancient question. In 2019, there's the constdeclaration that's supported just about everywhere. However note that like let, constscoping is different from varscoping.

编辑- 这是一个古老问题的古老答案。在 2019 年,const几乎所有地方都支持该宣言。但是请注意,像letconst范围界定与var范围界定不同。

回答by Ken

As "Pointy" so carefully notes, ECMAscript has no such feature. However, JavaScript does:

正如“Pointy”仔细指出的那样,ECMAscript 没有这样的功能。但是,JavaScript 确实

const a = 7;
document.writeln("a is " + a + ".");

Of course, if you're writing code to put on the web to run in web browsers, this might not help you much. :-)

当然,如果您正在编写代码放在网络上以在网络浏览器中运行,这可能对您没有多大帮助。:-)

回答by Josh K

Everything is global unless declared with the varkeyword.

除非用var关键字声明,否则一切都是全局的。

There are no constants either. You can simply declare them without the varkeyword.

也没有常数。您可以在没有var关键字的情况下简单地声明它们。

If you want to ensure global scope you can throw it into the windowobject:

如果你想确保全局范围,你可以把它扔到window对象中:

window.GLOBAL_CONSTANT = "value";

You can do this from within any scope. Constants can then be declared inside functions or closures, though I wouldn't recommend that.

您可以在任何范围内执行此操作。然后可以在函数或闭包中声明常量,但我不建议这样做。

回答by Stuffe

You could do it with getters and setters like so:

你可以像这样使用 getter 和 setter 来做到这一点:

Object.defineProperty(window, 'TAU', { 
    get: function(){return Math.PI*2;}
});

If you want a general function to do this:

如果你想要一个通用函数来做到这一点:

function define(name, value){
    Object.defineProperty(window, name, { 
       get: function(){return value;},
       set: function(){throw(name+' is a constant and cannot be redeclared.');},
    });
}

// Example use
define('TAU', Math.PI*2);

回答by kojow7

If you only care about supporting newer browsers (or are using a transpiler such as Babel to support older browsers) you can do the following:

如果您只关心支持较新的浏览器(或使用 Babel 等转译器来支持较旧的浏览器),您可以执行以下操作:

  1. Create a settings.js file with whatever constants you want and export them:
  1. 使用您想要的任何常量创建一个 settings.js 文件并导出它们:
export const FRUIT = "kiwi";
export const VEGETABLE = "carrot";
export const FRUIT = "kiwi";
export const VEGETABLE = "carrot";
  1. In files that you want to use them you could then import them as follows:
  1. 在您想要使用它们的文件中,您可以按如下方式导入它们:
import * as Settings from './settings.js'
import * as Settings from './settings.js'
  1. Then to use the constants do something like this:
  1. 然后使用常量做这样的事情:
console.log("The unchangeable fruit is " + Settings.FRUIT);
console.log("The unchangeable fruit is " + Settings.FRUIT);

This is a much cleaner approach than trying to implement a global constant, especially when you have multiple JavaScript files that you want to use the constants in.

与尝试实现全局常量相比,这是一种更简洁的方法,尤其是当您有多个要在其中使用常量的 JavaScript 文件时。

回答by leon

If you want to make sure the value cannot change use a function.

如果您想确保该值无法更改,请使用函数。

So, instead of:

所以,而不是:

var Const_X=12

use:

用:

function Const_X() {
return 12;
}

回答by Alvin Baldemeca

The direct answer to the question is No. It would really help though if ECMA/JS made a way to easily do functional programming. A workable hack I use to get around this is to declare a const in the global scope and use a wrapper function see example below:

这个问题的直接答案是否定的。不过,如果 ECMA/JS 提供一种轻松进行函数式编程的方法,那确实会有所帮助。我用来解决这个问题的一个可行的方法是在全局范围内声明一个 const 并使用一个包装函数,请参见下面的示例:

:)

:)

global_var = 3; //This can change say inside a function etc. but once you decide to make 
                //this global variable into a constant by calling on a function
const make_variable_constant = function(variable)
{
    const constant = variable;
    return constant;
}

const const_global = make_variable_constant(global_var);

:)

:)

Way back when object oriented programming was the hype a kid in my class told the C instructor that C isn't object oriented to which the instructor said he's done object oriented programming in C before Java and C++ were even conceived. Likewise you can do functional programming in Javascript but its much harder. Its like doing Object-oriented programming in C when its easier to do it in C++.

回到面向对象编程大肆宣传的时候,我班上的一个孩子告诉 C 讲师 C 不是面向对象的,讲师说他在 Java 和 C++ 被构思之前就已经用 C 完成了面向对象的编程。同样,您可以在 Javascript 中进行函数式编程,但要困难得多。这就像在 C 中进行面向对象编程,而在 C++ 中更容易进行。

回答by magallanes

For the record.

作为记录。

// ES6+ code:
const CONSTGLOBAL1=200;  // it is a constant global

function somef() { 
   document.write(CONSTGLOBAL1); // CONSTGLOBAL1 is defined (because it's global)
   const CONSTLOCAL=200; // it's a local constant
   document.write(CONSTLOCAL); // CONSTLOCAL is defined
}       
somef();
document.write(CONSTLOCAL); // CONSTLOCALis NOT defined.

So, if the constant is defined inside {} then it's local, otherwise, it's global.

因此,如果常量在 {} 中定义,则它是本地的,否则,它是全局的。