Access a constant inside an object in javascript

6

I am creating a custom event method, to do so I must 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 the outside I want to access EVENT_ON_USER_LOGIN . Something like this:

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

I can not access it either

console.log(EventManager.EVENT_ON_USER_LOGIN );
    
asked by Pablo 18.12.2016 в 20:53
source

5 answers

3

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'
    
answered by 19.12.2016 в 03:25
1

As far as I can not directly declare inside the function a constant and use outside the function. What if you can do something like what I show below. With Object.freeze (myConstant) it remains as constant and if you want to assign new values, it does not take it.

class miConstante {};
miConstante.EVENT_ON_USER_LOGIN = "EVENT_ON_USER_LOGIN";
Object.freeze(miConstante);

console.log("Valor de la constante: ", miConstante.EVENT_ON_USER_LOGIN );

// NO cambia el valor de la constante.
miConstante.EVENT_ON_USER_LOGIN = "Hola";
console.log("CAmbiar valor de la constante: ", miConstante.EVENT_ON_USER_LOGIN );

I hope it serves you.

    
answered by 18.12.2016 в 21:34
1

You can use the privileged methods as follows:

Private

function Constructor(value) {
   var that = this;
   var membername = value;
   var membername = function membername() {...};
}

Privileged

function Constructor(value) {
   var that = this;
   const memberName = value;
   this.methodMemberName = function () { return memberName; };
}

So in the following way for your example:

var EventManager = function(){
	const EVENT_ON_USER_LOGIN  = "EVENT_ON_USER_LOGIN";
    this.getEventOnUserLogin = function(){
       return EVENT_ON_USER_LOGIN;
    }
    this.EVENT_ON_USER_LOGIN = function(){
       return EVENT_ON_USER_LOGIN;
    } 
}

var eventManager = new EventManager();

console.log(eventManager.EVENT_ON_USER_LOGIN());
console.log(eventManager.getEventOnUserLogin());

In my case I prefer that the event be called getEventOnUserLogin .

You can find more information in the following link link

    
answered by 19.12.2016 в 16:15
1

One option you have is to freeze the object as suggested by josego using Object.freeze(variable) . In that link it is explained that:

  

The Object.freeze() method freezes an object: that is, it prevents new properties from being added; deprive the existing properties to be eliminated; and prevents existing properties, or their ability to enumerate, configure, or write. of being changed. In essence the object is made effectively immutable. The method returns the frozen object.

What you could do is define your object with the constants you need and then freeze it. The downside of this is that ALL the variables will be frozen, not just the ones you want to be constant. The functions would continue to function normally, so what you could do is define everything in an object and add a "constructor" to freeze it and return it (so that it can be standardized and used in the same way with more than one variable).

Here is an example:

var miObjeto = {
  // aquí irían las constantes
  EVENT_ON_USER_LOGIN: "EVENT_ON_USER_LOGIN",
 
  // aquí puedes poner funciones

  // el "constructor" que congelará y devolverá el objeto 
  constructor: function() {
    Object.freeze(this);
    return this;
  }
}

var em = miObjeto.constructor();
console.log(em.EVENT_ON_USER_LOGIN);

em.EVENT_ON_USER_LOGIN = "Un texto diferente";
console.log(em.EVENT_ON_USER_LOGIN);

Or if you want to leave it in the form of a function like you had at the beginning, you could do something like this:

function EventManager() {

    const obj = {
      EVENT_ON_USER_LOGIN: "EVENT_ON_USER_LOGIN"
    };
    
    return Object.freeze(obj);
  
}

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

em.EVENT_ON_USER_LOGIN = 12;
console.log(em.EVENT_ON_USER_LOGIN);
    
answered by 19.12.2016 в 15:54
1

You could do the following:

  • Object.defineProperty ( IE9+ ): This method allows you to add or modify a property in an object. Indicating writable: false , the property will be created read-only.

var EventManager = function(){
  //codigo
}

Object.defineProperty(EventManager, 'EVENT_ON_USER_LOGIN', {
  enumerable: false,
  configurable: false,
  writable: false,
  value: 1
});

console.log(EventManager.EVENT_ON_USER_LOGIN);
EventManager.EVENT_ON_USER_LOGIN = 2;
console.log(EventManager.EVENT_ON_USER_LOGIN);
  • ES6 : You can create read-only variables ( constants ) using the keyword const .

    const EVENT_ON_USER_LOGIN = 1;
    
      

    Unfortunately, this method can not be used to declare constants as object property.

    One way to get a result similar to the one proposed in the question, is using the syntax get combined with static .

class EventManager {

  static get EVENT_ON_USER_LOGIN() { return 1; }
}

console.log(EventManager.EVENT_ON_USER_LOGIN);
try {
 EventManager.EVENT_ON_USER_LOGIN = 2;
} catch(e) {
  console.log('ERROR!');
}
console.log(EventManager.EVENT_ON_USER_LOGIN);
    
answered by 19.12.2016 в 14:31