Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to declare class constants?

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 Foo laying 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 Foo is constructed?

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.

like image 770
Tom Tucker Avatar asked Jan 25 '11 02:01

Tom Tucker


People also ask

How do you declare a class constant in Java?

To make any variable a constant, we must use 'static' and 'final' modifiers in the following manner: Syntax to assign a constant value in java: static final datatype identifier_name = constant; The static modifier causes the variable to be available without an instance of it's defining class being loaded.

How do you declare a constant in a class in C++?

Const member functions in C++ Constant member functions are those functions which are denied permission to change the values of the data members of their class. To make a member function constant, the keyword “const” is appended to the function prototype and also to the function definition header.

How do you declare a constant in programming?

Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero.


8 Answers

All you're doing in your code is adding a property named CONSTANT with the value 1 to the Function object named Foo, then overwriting it immediately with the value 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.

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

Maybe you wanted to prototype some property onto Foo?

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

Not quite what you're after though.

like image 169
user113716 Avatar answered Sep 22 '22 05:09

user113716


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 not do that :

Foo.prototype.CONSTANT1 = 1;
like image 42
Soap Avatar answered Sep 20 '22 05:09

Soap


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.

like image 20
Scott van Looy Avatar answered Sep 18 '22 05:09

Scott van Looy


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

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
like image 29
Marius Balčytis Avatar answered Sep 22 '22 05:09

Marius Balčytis


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

like image 20
hvgotcodes Avatar answered Sep 19 '22 05:09

hvgotcodes


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:

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 CONSTANT1 statement 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.)

like image 45
Scott Weldon Avatar answered Sep 21 '22 05:09

Scott Weldon


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;
    }
};
like image 22
Amc_rtty Avatar answered Sep 19 '22 05:09

Amc_rtty


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

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

To get the taste of Javascript, find Javascript: the Good Parts and learn the idiomatic ways. Javascript is very different from Java.

like image 30
9000 Avatar answered Sep 20 '22 05:09

9000