Object oriented javascript how to create a static class for constants

I decided to put all my constants in a class class called constants, and would like to access its members using the dot operator.

So far I have tried:

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

And later

 Constants = new Constants(); 

and

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

This led to

Unable to access button_width from undefined.

I would use JSON to declare constants, but I like the comments in my code. Anyone explain javascript OO?

+4
source share
4 answers

You are replacing the Constants function with an instance of Constants . And you applied your constants to a function, not to an instance of constants or a prototype. Thus, you have effectively destroyed your constants.

I would say just use an object literal

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

Keep in mind that there is practically nothing on any of the approaches. Anyone can easily change the "constant" values. If you want truly persistent data, you can use getters / setters, Object.defineProperty or a module template.

+5
source

If you need a β€œclass” with static and instances:

 function ClassName(){ } ClassName.prototype = { //Put instance methods here instanceMethod1 : function(){}, instanceMethod2 : function(){} }; ClassName.staticMethod1 = function(){}; ClassName.staticMethod2 = function(){}; var a = new ClassName(); a.staticMethod1; //undefined a.instanceMethod1; //function(){}; ClassName.staticMethod1 //function(){}; 
+5
source

Why don't you just use literals?

 var Constants = { style: { border_sides: 20, button_width: 17 } } 

Even if you want to consider using the construction function , replace Constants with this

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

You do not need to do new Constants() for literals (1st example). Just start using right away.

For the second example (constructor function) you need to do var constants = new Constants() .

+4
source

In Javascript, every object is an object, so you add properties to the Constants function inside the function.

To get the effect you want to record:

 var Constants = { someText: 'text1', someInt: 1 }; 

And for access just:

 var text = Constants.someText; 
+2
source

Source: https://habr.com/ru/post/1380803/


All Articles