Javascript 在哪里声明类常量?

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

Where to declare class constants?

javascriptconventions

提问by Tom Tucker

I'm using class members to hold constants. E.g.:

我正在使用类成员来保存常量。例如:

function Foo() {
}

Foo.CONSTANT1 = 1;
Foo.CONSTANT2 = 2;

This works fine, except that it seems a bit unorganized, with all the code that is specific to Foolaying around in global scope. So I thought about moving the constant declaration to inside the Foo()declaration, but then wouldn't that code execute everytime Foois constructed?

这工作得很好,除了它似乎有点无组织,所有特定于Foo在全局范围内放置的代码。所以我想将常量声明移到声明内部Foo(),但是每次Foo构造时都不会执行该代码吗?

I'm coming from Java where everything is enclosed in a class body, so I'm thinking JavaScript might have something similar to that or some work around that mimics it.

我来自 Java,其中所有内容都包含在一个类主体中,所以我认为 JavaScript 可能有类似的东西或一些模仿它的工作。

回答by user113716

All you're doing in your code is adding a property named CONSTANTwith the value 1to the Function object named Foo, then overwriting it immediately with the value 2.

您在代码中所做的就是将一个以CONSTANT该值命名的属性添加1到名为 Foo 的 Function 对象中,然后立即用该值覆盖它2

I'm not too familiar with other languages, but I don't believe javascript is able to do what you seem to be attempting.

我对其他语言不太熟悉,但我不相信 javascript 能够做你似乎正在尝试的事情。

None of the properties you're adding to Foowill ever execute. They're just stored in that namespace.

您添加的Foo任何属性都不会执行。它们只是存储在该命名空间中。

Maybe you wanted to prototype some property onto Foo?

也许您想将某些属性原型化到Foo?

function Foo() {
}

Foo.prototype.CONSTANT1 = 1;
Foo.prototype.CONSTANT2 = 2;

Not quite what you're after though.

不完全是你所追求的。

回答by Soap

You must make your constants like you said :

你必须像你说的那样做你的常数:

function Foo() {
}

Foo.CONSTANT1 = 1;
Foo.CONSTANT2 = 2;

And you access like that :

你可以这样访问:

Foo.CONSTANT1;

or

或者

anInstanceOfFoo.__proto__.constructor.CONSTANT1;

All other solutions alloc an other part of memory when you create an other object, so it's not a constant. You should notdo that :

当您创建其他对象时,所有其他解决方案都会分配另一部分内存,因此它不是常量。你不应该这样做:

Foo.prototype.CONSTANT1 = 1;

回答by Scott van Looy

IF the constants are to be used inside of the object only:

如果常量仅在对象内部使用:

function Foo() {
    var CONSTANT1 = 1,CONSTANT2 = 2;
}

If not, do it like this:

如果没有,请这样做:

function Foo(){
    this.CONSTANT1=1;
    this.CONSTANT2=2;
}

It's much more readable and easier to work out what the function does.

它更具可读性,更容易计算出函数的作用。

回答by Marius Bal?ytis

If you're using jQuery, you can use $.extend function to categorize everything.

如果您使用的是 jQuery,则可以使用 $.extend 函数对所有内容进行分类。

var MyClass = $.extend(function() {
        $.extend(this, {
            parameter: 'param',
            func: function() {
                console.log(this.parameter);
            }
        });
        // some code to do at construction time
    }, {
        CONST: 'const'
    }
);
var a = new MyClass();
var b = new MyClass();
b.parameter = MyClass.CONST;
a.func();       // console: param
b.func();       // console: const

回答by hvgotcodes

what you are doing is fine (assuming you realize that your example is just setting the same property twice); it is the equivalent of a static variable in Java (as close as you can get, at least without doing a lot of work). Also, its not entirely global, since its on the constructor function, it is effectively namespaced to your 'class'.

你在做什么很好(假设你意识到你的例子只是设置了两次相同的属性);它相当于 Java 中的静态变量(尽可能接近,至少无需做很多工作)。此外,它并不完全是全局的,因为它在构造函数上,它有效地命名为您的“类”。

回答by Scott Weldon

First, I recommend moving your class declaration inside of an IIFE. This cleans up the code, making it more self-contained, and allows you to use local variables without polluting the global namespace. Your code becomes:

首先,我建议将您的类声明移到 IIFE 中。这会清理代码,使其更加独立,并允许您在不污染全局命名空间的情况下使用局部变量。您的代码变为:

var Foo = (function() {
  function Foo() {
  }

  Foo.CONSTANT1 = 1;
  Foo.CONSTANT2 = 2;

  return Foo;
})();

The problem with assigning constants directly to the class as attributes is that those are writable. See this snippet:

将常量作为属性直接分配给类的问题在于它们是可写的。看到这个片段:

var output = document.getElementById("output");

var Foo = (function() {
  function Foo() {
  }

  Foo.CONSTANT1 = 1;
  Foo.CONSTANT2 = 2;

  return Foo;
})();

Foo.CONSTANT1 = "I'm not very constant";

output.innerHTML = Foo.CONSTANT1;
<div id="output"></div>

The best solution I have found is to define read-only properties for accessing the constants outside of the class.

我发现的最佳解决方案是定义只读属性以访问类外的常量。

var output = document.getElementById("output");

var Foo = (function() {
  const CONSTANT1 = "I'm very constant";

  function Foo() {
  }

  Object.defineProperty(Foo, "CONSTANT1", {
    get: function() {
      return CONSTANT1;
    },
  });

  return Foo;
})();

Foo.CONSTANT1 = "some other value";

output.innerHTML = Foo.CONSTANT1;
<div id="output"></div>

(Technically you could ditch the const CONSTANT1statement and just return the value from the property definition, but I prefer this because it makes it easier to see all the constants at a glance.)

(从技术上讲,您可以放弃该const CONSTANT1语句并仅从属性定义中返回值,但我更喜欢这样做,因为这样可以更轻松地一目了然地查看所有常量。)

回答by 9000

Your constants are just variables, and you won't know if you try and inadvertently overwrite them. Also note that Javascript lacks the notion of "class".

您的常量只是变量,如果您尝试无意中覆盖它们,您将不知道。另请注意,Javascript 缺少“类”的概念。

I'd suggest you create functions that return values that you need constant.

我建议您创建返回需要常量的值的函数。

To get the taste of Javascript, find Javascript: the Good Partsand learn the idiomatic ways. Javascript is verydifferent from Java.

要体验 Javascript,请查找Javascript: the Good Parts并学习惯用的方法。Javascript与 Java非常不同。

回答by Amc_rtty

Also with namespaces

也有命名空间

var Constants = {
    Const1: function () {
        Const1.prototype.CONSTANT1 = 1;
        Const1.prototype.CONSTANT2 = 2;
    },

    Const2: function () {
        Const2.prototype.CONSTANT3 = 4;
        Const2.prototype.CONSTANT4 = 3;
    }
};

回答by Srneczek

You said your coming from Java - why don't you store that class in 1 file then and constants at the end of the file. This is what I use:

您说您来自 Java - 为什么不将该类存储在 1 个文件中,然后将常量存储在文件末尾。这是我使用的:

filename: PopupWindow.js

文件名:PopupWindow.js

function PopupWindow() {
    //private class memebers
    var popup, lightbox;
    //public class memeber or method (it is the same in JS if I am right)
    this.myfuncOrmyMemeber = function() {};
}

//static variable
PopupWindow._instance = null;
//same thing again with constant-like name (you can't have "final" in JS if I am right, so it is not immutable constant but its close enough ;) - just remember not to set varibales with BIG_LETTERS :D)
PopupWindow.MY_CONSTANT = 1;
//yea, and same thing with static methods again
PopupWindow._getInstance = function() {};

So only difference is the position of static stuff. It is not nicly aligned inside class curly braces, but who cares, its always ctrl+click in IDE (or I use ctr+l to show all class methods - IntellijIdea can do that in JS dunno how about other IDEs) so your not gonna search it by your eye ;)

所以唯一的区别是静态东西的位置。它在类花括号内没有很好地对齐,但谁在乎,它总是在 IDE 中按 ctrl+click(或者我使用 ctr+l 来显示所有类方法 - IntellijIdea 可以在 JS 中做到这一点,不知道其他 IDE 怎么样)所以你不会用眼睛搜索它;)

Yea and I use _ before static method - it is not needed, I don't know why I started to do that :)

是的,我在静态方法之前使用 _ - 它不需要,我不知道为什么我开始这样做:)