有条件地在 Javascript 中初始化一个常量

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

Conditionally initializing a constant in Javascript

javascriptecmascript-6constants

提问by Frozen Crayon

ES6 onwards we have const.

从 ES6 开始,我们有const.

This is not allowed:

这是不允许的:

const x; //declare first
//and then initialize it
if(condition) x = 5;
else x = 10;

This makes sense because it prevents us from using the constant before it's initialized.

这是有道理的,因为它阻止我们在初始化之前使用常量。

But if I do

但如果我这样做

if(condition)
    const x = 5;

else 
    const x = 10;

x becomes block scoped.

x 变为块作用域。

So how to conditionally create a constant?

那么如何有条件地创建一个常量呢?

回答by Hecksa

Your problem, as you know, is that a consthas to be intialised in the same statement that it was declared in.

如您所知,您的问题是 aconst必须在声明它的同一语句中初始化。

This doesn't mean that the value you assign to your constant has to be a literal value. It could be any valid statement really - ternary:

这并不意味着您分配给常量的值必须是文字值。它可能是任何有效的陈述 - 三元:

const x = IsSomeValueTrue() ? 1 : 2;

Or maybe just assign it to the value of a variable?

或者也许只是将它分配给变量的值?

let y = 1;
if(IsSomeValueTrue()) {
    y = 2;
}

const x = y;

You could of course assign it to the return value of a function, too:

您当然也可以将其分配给函数的返回值:

function getConstantValue() {
    return 3;
}

const x = getConstantValue();

So there's plenty of ways to make the value dynamic, you just have to make sure it's only assigned in one place.

所以有很多方法可以使值动态化,您只需要确保它只分配在一个地方。

回答by Estus Flask

If ternary operator isn't an option for its unreadability, the only other option is IIFE, which is cumbersome but can be read fluently:

如果三元运算符的不可读性不是一个选项,那么唯一的其他选项是 IIFE,它很麻烦但可以流畅地阅读:

const x = (() => {
  if (condition)
    return 5
  else
    return 10
})();

The semantics of constis that it is assigned once. It should be letfor this use case:

的语义const是它被分配一次。它应该let适用于这个用例:

let x;
if(condition) x = 5;
else x = 10;

From my personal experience, ~95% of variables are const. If a variable has to be be let, just let it be itself; the probability of bugs caused by accidental reassignments is negligible.

根据我的个人经验,约 95% 的变量是const. 如果一个变量必须是let,就让它成为它自己;由意外重新分配引起的错误的可能性可以忽略不计。

回答by CodingIntrigue

Assuming that the constis going to be declared in bothinstances, you could use a ternary assignment:

假设const将在两种情况下声明,您可以使用三元赋值:

const x = condition ? 5 : 10;

回答by Ala Eddine JEBALI

I suggest this solution with a Singleton Patternimplementation:

我建议使用单例模式实现这个解决方案:

var Singleton = (function () {
    var instance;

    function createInstance() {
        // all your logic here
        // so based on your example:
        // if(condition) return 5;
        // else return 10;
    }

    return {
        getInstance: function () {
            if (!instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
})();

const x = Singleton.getInstance();