Access a constant within an object in javascript

Question:

I am creating a custom event method, to do it I need to create the event types as constants. My question is how to access a constant within an object.

Example:

var EventManager=function() {
    const EVENT_ON_USER_LOGIN = "EVENT_ON_USER_LOGIN";
};

from outside I want to access EVENT_ON_USER_LOGIN . Something like that:

var eventManager = new EventManager();
console.log(eventManager.EVENT_ON_USER_LOGIN );

I can't access like this either

console.log(EventManager.EVENT_ON_USER_LOGIN );

Answer:

You can do this:

var EventManager = function(){
  //codigo
}

EventManager.EVENT_ON_USER_LOGIN = 'EVENT_ON_USER_LOGIN';

//y lo podrías usar así:
var eManager = new EventManager();
EventManager.EVENT_ON_USER_LOGIN;

@Josego's answer could work for you too.

//De esta manera los objetos que se definan tendrán la propiedad 'EVENTS' con los tipos de eventos y serán inmutables 
var EventManager = function(){
    var events = {
        EVENT_ON_USER_LOGIN: 'EVENT_ON_USER_LOGIN'
    };
    this.EVENTS = Object.freeze( events );
};
//
var eventManaget = new EventManager();
eventManager.EVENTS.EVENT_ON_USER_LOGIN;  //'EVENT_ON_USER_LOGIN'

Or you could return a 'frozen' object with Object.freeze

var EventManager = function(){
    var eventManager = function(){
        this.EVENT_ON_USER_LOGIN = 'EVENT_ON_USER_LOGIN';
    };
    return Object.freeze( new eventManager() );
};
var eventManager = new EventManager();
eventManager.EVENT_ON_USER_LOGIN; //   'EVENT_ON_USER_LOGIN'
Scroll to Top