Object-oriented JavaScript how to create a static class for constants

I decided to put all the constants in a concise class called constants, and wanted to use the dot operator to access its members.

So far , I have tried:

function Constants(){
Constants.style = {};
Constants.style.border_sides = 20;
Constants.style.button_width = 17;
// ...
}

Then

Constants = new Constants ();

and

{
$('#button').width(Constants.style.button_width);
}

This resulted in a

Can’t access button_width of undefined.

I Will use JSON to declare constants, but I like the comments in my code.
Can anyone explain the OO of javascript?

Replace constant functions with constant instances. And you apply constants to functions, not constants or prototypes Instance. So you effectively erased your constants.

I think only one object literal is used

var constants = { 
style: {
border_sides: 20
}
};

Please remember that neither method has any practical meaning. Anyone can Easily change the “constant” value. If you want real constant data, you may need to use getter/setter, Object.defineProperty or module mode.

I decided to change all The constants are placed in a concise class called constants, and I want to use the dot operator to access its members.

So far, I have tried:

function Constants(){
Constants.style = {};
Constants.style.border_sides = 20;
Constants.style.button_width = 17;
/ / ...
}

Then

Constants = new Constants();

and

{
$('#button').width(Constants.style.button_width);
}

This resulted in a

Can’t access button_width of undefined.

I use JSON to declare constants, but I like comments in my code .
Will anyone explain the OO of javascript?

Replace constant functions with constant instances. And you apply constants to functions, not instances of constants or prototypes. So you effectively erased your Constants.

I think only one object literal is used

var constants = {
style: {
border_sides : 20
}
};

Remember that neither of these two methods have any practical meaning. Anyone can easily change the “constant” value. If you want a real For constant data, you may need to use getter/setter, Object.defineProperty or module mode.

Leave a Comment

Your email address will not be published.