Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

object oriented javascript how to create a static class for constants

Tags:

javascript

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

So far I've 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);
}

That resulted in a

Can't access button_width of undefined.

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

like image 749
lowerkey Avatar asked Dec 05 '22 19:12

lowerkey


2 Answers

You replace the Constants function with an instance of Constants. And you applied your constants to the function, not an instance of Constants or the prototype. So you effectively wiped your constants away.

I'd argue just use an object literal

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

Keep in mind there's nothing actually constant about either approaches. Anyone can easily change the "constant" values. If you want truly constant data, you might want to use getters/setters, Object.defineProperty or the module pattern.

like image 104
Matt Greer Avatar answered Dec 22 '22 00:12

Matt Greer


If you want a "class" with both static and instance methods:

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(){};
like image 35
Esailija Avatar answered Dec 21 '22 23:12

Esailija