Hay constantes en JavaScript?


¿Hay alguna forma de usar constantes en JavaScript?

Si no, ¿cuál es la práctica común para especificar variables que se utilizan como constantes?

Author: Steven Vascellaro, 2008-09-25

30 answers

Ya que ES2015, JavaScript tiene una noción de const:

const MY_CONSTANT = "some-value";

Esto funcionará en casi todos los navegadores excepto IE 8, 9 y 10. Algunos también pueden necesitar modo estricto habilitado.

Puede usar var con convenciones como ALL_CAPS para mostrar que ciertos valores no deben modificarse si necesita admitir navegadores antiguos o está trabajando con código heredado:

var MY_CONSTANT = "some-value";
 971
Author: John Millikin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-04 06:33:41

¿Está tratando de proteger las variables contra la modificación? Si es así, entonces puede usar un patrón de módulo:

var CONFIG = (function() {
     var private = {
         'MY_CONST': '1',
         'ANOTHER_CONST': '2'
     };

     return {
        get: function(name) { return private[name]; }
    };
})();

alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1

CONFIG.MY_CONST = '2';
alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1

CONFIG.private.MY_CONST = '2';                 // error
alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1

Usando este enfoque, los valores no se pueden modificar. Pero, tienes que usar el método get () en CONFIG: (.

Si no necesita proteger estrictamente el valor de las variables, simplemente haga lo sugerido y use una convención de TODAS las MAYÚSCULAS.

 304
Author: Burke,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-25 03:14:30

La palabra clave const está en el borrador de ECMAScript 6 pero hasta ahora solo disfruta de un poco de soporte para navegadores: http://kangax.github.io/compat-table/es6 / . La sintaxis es:

const CONSTANT_NAME = 0;
 119
Author: Bill the Lizard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-08 10:43:18
"use strict";

var constants = Object.freeze({
    "π": 3.141592653589793 ,
    "e": 2.718281828459045 ,
    "i": Math.sqrt(-1)
});

constants.π;        // -> 3.141592653589793
constants.π = 3;    // -> TypeError: Cannot assign to read only property 'π' …
constants.π;        // -> 3.141592653589793

delete constants.π; // -> TypeError: Unable to delete property.
constants.π;        // -> 3.141592653589793

Ver Objeto.congelar. Puede utilizar const si desea hacer que la referencia constants también sea de solo lectura.

 64
Author: sam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-24 19:58:43

IE soporta constantes, por ejemplo:

<script language="VBScript">
 Const IE_CONST = True
</script>
<script type="text/javascript">
 if (typeof TEST_CONST == 'undefined') {
    const IE_CONST = false;
 }
 alert(IE_CONST);
</script>
 63
Author: C Nagle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-26 19:22:46

ECMAScript 5 introduce Object.defineProperty:

Object.defineProperty (window,'CONSTANT',{ value : 5, writable: false });

Es compatible con todos los navegadores modernos (así como IE ≥ 9).

Véase también: Objeto.defineProperty en ES5?

 57
Author: Not a Name,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-02 17:52:17

No, no en general. Firefox implementa const pero sé que IE no.


@John apunta a una práctica de nomenclatura común para los conss que se ha utilizado durante años en otros idiomas, no veo ninguna razón por la que no pueda usar eso. Por supuesto, eso no significa que alguien no escribirá sobre el valor de la variable de todos modos. :)

 24
Author: Jason Bunting,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:29

Los documentos web de Mozillas MDN contienen buenos ejemplos y explicaciones sobre const. Extracto:

// define MY_FAV as a constant and give it the value 7
const MY_FAV = 7;

// this will throw an error - Uncaught TypeError: Assignment to constant variable.
MY_FAV = 20;

Pero es triste que IE9/10 todavía no soporta const. Y la razón es absurdo:

Entonces, ¿qué está haciendo IE9 con const? Tan lejos, nuestra decisión ha sido no apóyalo. Todavía no es un consenso característica ya que nunca ha estado disponible en todos los navegadores.

...

Al final, parece que el mejor a largo plazo solución para la web es dejarlo y esperar a que procesos de estandarización para ejecutar su curso.

¿No lo implementan porque otros navegadores no lo implementaron correctamente?! ¿Demasiado miedo de mejorarlo? Definiciones de estándares o no, una constante es una constante: se establece una vez, nunca se cambia.

Y a todas las ideas: Cada función puede ser sobrescrita (XSS etc.). Así que no hay diferencia en var o function(){return}. const es el único verdadero constante.

Actualizar: IE11 soporta const:

IE11 incluye soporte para las características bien definidas y comúnmente usadas del emergente estándar ECMAScript 6 incluyendo let, const, Map, Set, y WeakMap, así como __proto__ para mejorar la interoperabilidad.

 20
Author: mgutt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-15 10:04:14

En JavaScript, mi preferencia es usar funciones para devolver valores constantes.

function MY_CONSTANT() {
   return "some-value";
}


alert(MY_CONSTANT());
 18
Author: MTS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-24 19:46:52

Si no te importa usar funciones:

var constant = function(val) {
   return function() {
        return val;
    }
}

Este enfoque le da funciones en lugar de variables regulares, pero garantiza* que nadie puede alterar el valor una vez que se establece.

a = constant(10);

a(); // 10

b = constant(20);

b(); // 20

Personalmente encuentro esto bastante agradable, especialmente después de habernos acostumbrado a este patrón de knockout observables.

*A menos que alguien redefiniera la función constant antes de llamarla

 17
Author: hasen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-30 19:42:39

Con la api de objetos "new" puedes hacer algo como esto:

var obj = {};
Object.defineProperty(obj, 'CONSTANT', {
  configurable: false
  enumerable: true,
  writable: false,
  value: "your constant value"
});

Echa un vistazo a this en la MDN de Mozilla para más detalles. No es una variable de primer nivel, ya que está unida a un objeto, pero si tienes un ámbito, cualquier cosa, puedes adjuntarlo a eso. this debería funcionar también. Así, por ejemplo, hacer esto en el ámbito global declarará un valor pseudo constante en la ventana (que es una muy mala idea, no debe declarar VAR globales por descuido)

Object.defineProperty(this, 'constant', {
  enumerable: true, 
  writable: false, 
  value: 7, 
  configurable: false
});

> constant
=> 7
> constant = 5
=> 7

Nota: la asignación le devolverá el valor asignado en la consola, pero el valor de la variable no cambiará

 17
Author: tenshou,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-28 08:37:36

Agrupar constantes en estructuras cuando sea posible:

Ejemplo, en mi proyecto de juego actual, he utilizado a continuación:

var CONST_WILD_TYPES = {
    REGULAR: 'REGULAR',
    EXPANDING: 'EXPANDING',
    STICKY: 'STICKY',
    SHIFTING: 'SHIFTING'
};

Asignación:

var wildType = CONST_WILD_TYPES.REGULAR;

Comparación:

if (wildType === CONST_WILD_TYPES.REGULAR) {
    // do something here
}

Más recientemente estoy usando, para comparación:

switch (wildType) {
    case CONST_WILD_TYPES.REGULAR:
        // do something here
        break;
    case CONST_WILD_TYPES.EXPANDING:
        // do something here
        break;
}

IE11 está con el nuevo estándar ES6 que tiene declaración 'const'.
Arriba funciona en navegadores anteriores como IE8, IE9 e IE10.

 14
Author: Manohar Reddy Poreddy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-10 02:06:43

Puede equipar fácilmente su script con un mecanismo para constantes que se pueden establecer pero no alterar. Un intento de alterarlos generará un error.

/* author Keith Evetts 2009 License: LGPL  
anonymous function sets up:  
global function SETCONST (String name, mixed value)  
global function CONST (String name)  
constants once set may not be altered - console error is generated  
they are retrieved as CONST(name)  
the object holding the constants is private and cannot be accessed from the outer script directly, only through the setter and getter provided  
*/

(function(){  
  var constants = {};  
  self.SETCONST = function(name,value) {  
      if (typeof name !== 'string') { throw new Error('constant name is not a string'); }  
      if (!value) { throw new Error(' no value supplied for constant ' + name); }  
      else if ((name in constants) ) { throw new Error('constant ' + name + ' is already defined'); }   
      else {   
          constants[name] = value;   
          return true;  
    }    
  };  
  self.CONST = function(name) {  
      if (typeof name !== 'string') { throw new Error('constant name is not a string'); }  
      if ( name in constants ) { return constants[name]; }    
      else { throw new Error('constant ' + name + ' has not been defined'); }  
  };  
}())  


// -------------  demo ----------------------------  
SETCONST( 'VAT', 0.175 );  
alert( CONST('VAT') );


//try to alter the value of VAT  
try{  
  SETCONST( 'VAT', 0.22 );  
} catch ( exc )  {  
   alert (exc.message);  
}  
//check old value of VAT remains  
alert( CONST('VAT') );  


// try to get at constants object directly  
constants['DODO'] = "dead bird";  // error  
 12
Author: Keith,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-01 15:46:37

Olvida IE y usa la palabra clave const.

 11
Author: Derek 朕會功夫,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-23 21:01:29

Sin embargo , no hay una forma predefinida exacta de hacerlo, puede lograrlo controlando el alcance de las variables como se muestra en otras respuestas.

Pero sugeriré usar el espacio de nombres para distinguir de otras variables. esto reducirá la posibilidad de colisión al mínimo de otras variables.

Espacio de nombres propio como

var iw_constant={
     name:'sudhanshu',
     age:'23'
     //all varibale come like this
}

Así que mientras se usa será iw_constant.name o iw_constant.age

También puede bloquear la adición de cualquier clave nueva o cambiar cualquier clave dentro de iw_constant usando Objeto.método de congelación. Sin embargo, no es compatible con el navegador heredado.

Ex:

Object.freeze(iw_constant);

Para un navegador más antiguo puede usar polyfill para el método de congelación.


Si está de acuerdo con la función de llamada siguiente es la mejor forma de cross browser para definir constante. El alcance de su objeto dentro de una función de ejecución automática y devolver una función get para sus constantes ex:

var iw_constant= (function(){
       var allConstant={
             name:'sudhanshu',
             age:'23'
             //all varibale come like this

       };

       return function(key){
          allConstant[key];
       }
    };

/ / para obtener el valor use iw_constant('name') o iw_constant('age')


** En ambos ejemplos tienes que tenga mucho cuidado con el espaciado de nombres para que su objeto o función no se reemplace a través de otra biblioteca.(Si el objeto o la función en sí mismo se reemplazará, su constante completa irá)

 9
Author: Sudhanshu Yadav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:45

Por un tiempo, especificé "constantes" (que todavía no eran constantes) en literales de objetos pasados a las sentencias with(). Pensé que era muy inteligente. He aquí un ejemplo:

with ({
    MY_CONST : 'some really important value'
}) {
    alert(MY_CONST);
}

En el pasado, también he creado un espacio de nombres CONST donde pondría todas mis constantes. Otra vez, con la sobrecarga. Sheesh.

Ahora, solo hago var MY_CONST = 'whatever'; para BESAR.

 7
Author: Andrew Hedges,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-24 23:29:59

Mi opinión (funciona solo con objetos).

var constants = (function(){
  var a = 9;

  //GLOBAL CONSTANT (through "return")
  window.__defineGetter__("GCONST", function(){
    return a;
  });

  //LOCAL CONSTANT
  return {
    get CONST(){
      return a;
    }
  }
})();

constants.CONST = 8; //9
alert(constants.CONST); //9

¡Inténtalo! Pero entender - esto es objeto, pero no variable simple.

Intenta también:

const a = 9;
 6
Author: user1635543,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-29 09:22:06

Yo también he tenido un problema con esto. Y después de bastante tiempo buscando la respuesta y mirando todas las respuestas de todos, creo que he encontrado una solución viable para esto.

Parece que la mayoría de las respuestas que he encontrado es utilizar funciones para mantener las constantes. Como muchos de los usuarios de los MUCHOS foros publican sobre, las funciones pueden ser fácilmente sobre escrito por los usuarios en el lado del cliente. Me intrigó la respuesta de Keith Evetts de que el objeto de constantes no puede ser accedido por el exterior, pero solo desde las funciones en el interior.

Así que se me ocurrió esta solución:

Poner todo dentro de una función anónima de esa manera, las variables, objetos, etc. el cliente no puede cambiarlo. También oculte las funciones ' reales 'haciendo que otras funciones llamen a las funciones' reales ' desde el interior. También pensé en usar funciones para comprobar si una función ha sido cambiada por un usuario en el lado del cliente. Si las funciones han sido cambiadas, cambie los devuelven usando variables que están 'protegidas' en el interior y no se pueden cambiar.

/*Tested in: IE 9.0.8; Firefox 14.0.1; Chrome 20.0.1180.60 m; Not Tested in Safari*/

(function(){
  /*The two functions _define and _access are from Keith Evetts 2009 License: LGPL (SETCONST and CONST).
    They're the same just as he did them, the only things I changed are the variable names and the text
    of the error messages.
  */

  //object literal to hold the constants
  var j = {};

  /*Global function _define(String h, mixed m). I named it define to mimic the way PHP 'defines' constants.
    The argument 'h' is the name of the const and has to be a string, 'm' is the value of the const and has
    to exist. If there is already a property with the same name in the object holder, then we throw an error.
    If not, we add the property and set the value to it. This is a 'hidden' function and the user doesn't
    see any of your coding call this function. You call the _makeDef() in your code and that function calls
    this function.    -    You can change the error messages to whatever you want them to say.
  */
  self._define = function(h,m) {
      if (typeof h !== 'string') { throw new Error('I don\'t know what to do.'); }
      if (!m) { throw new Error('I don\'t know what to do.'); }
      else if ((h in j) ) { throw new Error('We have a problem!'); }
      else {
          j[h] = m;
          return true;
    }
  };

  /*Global function _makeDef(String t, mixed y). I named it makeDef because we 'make the define' with this
    function. The argument 't' is the name of the const and doesn't need to be all caps because I set it
    to upper case within the function, 'y' is the value of the value of the const and has to exist. I
    make different variables to make it harder for a user to figure out whats going on. We then call the
    _define function with the two new variables. You call this function in your code to set the constant.
    You can change the error message to whatever you want it to say.
  */
  self._makeDef = function(t, y) {
      if(!y) { throw new Error('I don\'t know what to do.'); return false; }
      q = t.toUpperCase();
      w = y;
      _define(q, w);
  };

  /*Global function _getDef(String s). I named it getDef because we 'get the define' with this function. The
    argument 's' is the name of the const and doesn't need to be all capse because I set it to upper case
    within the function. I make a different variable to make it harder for a user to figure out whats going
    on. The function returns the _access function call. I pass the new variable and the original string
    along to the _access function. I do this because if a user is trying to get the value of something, if
    there is an error the argument doesn't get displayed with upper case in the error message. You call this
    function in your code to get the constant.
  */
  self._getDef = function(s) {
      z = s.toUpperCase();
      return _access(z, s);
  };

  /*Global function _access(String g, String f). I named it access because we 'access' the constant through
    this function. The argument 'g' is the name of the const and its all upper case, 'f' is also the name
    of the const, but its the original string that was passed to the _getDef() function. If there is an
    error, the original string, 'f', is displayed. This makes it harder for a user to figure out how the
    constants are being stored. If there is a property with the same name in the object holder, we return
    the constant value. If not, we check if the 'f' variable exists, if not, set it to the value of 'g' and
    throw an error. This is a 'hidden' function and the user doesn't see any of your coding call this
    function. You call the _getDef() function in your code and that function calls this function.
    You can change the error messages to whatever you want them to say.
  */
  self._access = function(g, f) {
      if (typeof g !== 'string') { throw new Error('I don\'t know what to do.'); }
      if ( g in j ) { return j[g]; }
      else { if(!f) { f = g; } throw new Error('I don\'t know what to do. I have no idea what \''+f+'\' is.'); }
  };

  /*The four variables below are private and cannot be accessed from the outside script except for the
    functions inside this anonymous function. These variables are strings of the four above functions and
    will be used by the all-dreaded eval() function to set them back to their original if any of them should
    be changed by a user trying to hack your code.
  */
  var _define_func_string = "function(h,m) {"+"      if (typeof h !== 'string') { throw new Error('I don\\'t know what to do.'); }"+"      if (!m) { throw new Error('I don\\'t know what to do.'); }"+"      else if ((h in j) ) { throw new Error('We have a problem!'); }"+"      else {"+"          j[h] = m;"+"          return true;"+"    }"+"  }";
  var _makeDef_func_string = "function(t, y) {"+"      if(!y) { throw new Error('I don\\'t know what to do.'); return false; }"+"      q = t.toUpperCase();"+"      w = y;"+"      _define(q, w);"+"  }";
  var _getDef_func_string = "function(s) {"+"      z = s.toUpperCase();"+"      return _access(z, s);"+"  }";
  var _access_func_string = "function(g, f) {"+"      if (typeof g !== 'string') { throw new Error('I don\\'t know what to do.'); }"+"      if ( g in j ) { return j[g]; }"+"      else { if(!f) { f = g; } throw new Error('I don\\'t know what to do. I have no idea what \\''+f+'\\' is.'); }"+"  }";

  /*Global function _doFunctionCheck(String u). I named it doFunctionCheck because we're 'checking the functions'
    The argument 'u' is the name of any of the four above function names you want to check. This function will
    check if a specific line of code is inside a given function. If it is, then we do nothing, if not, then
    we use the eval() function to set the function back to its original coding using the function string
    variables above. This function will also throw an error depending upon the doError variable being set to true
    This is a 'hidden' function and the user doesn't see any of your coding call this function. You call the
    doCodeCheck() function and that function calls this function.    -    You can change the error messages to
    whatever you want them to say.
  */
  self._doFunctionCheck = function(u) {
      var errMsg = 'We have a BIG problem! You\'ve changed my code.';
      var doError = true;
      d = u;
      switch(d.toLowerCase())
      {
           case "_getdef":
               if(_getDef.toString().indexOf("z = s.toUpperCase();") != -1) { /*do nothing*/ }
               else { eval("_getDef = "+_getDef_func_string); if(doError === true) { throw new Error(errMsg); } }
               break;
           case "_makedef":
               if(_makeDef.toString().indexOf("q = t.toUpperCase();") != -1) { /*do nothing*/ }
               else { eval("_makeDef = "+_makeDef_func_string); if(doError === true) { throw new Error(errMsg); } }
               break;
           case "_define":
               if(_define.toString().indexOf("else if((h in j) ) {") != -1) { /*do nothing*/ }
               else { eval("_define = "+_define_func_string); if(doError === true) { throw new Error(errMsg); } }
               break;
           case "_access":
               if(_access.toString().indexOf("else { if(!f) { f = g; }") != -1) { /*do nothing*/ }
               else { eval("_access = "+_access_func_string); if(doError === true) { throw new Error(errMsg); } }
               break;
           default:
                if(doError === true) { throw new Error('I don\'t know what to do.'); }
      }
  };

  /*Global function _doCodeCheck(String v). I named it doCodeCheck because we're 'doing a code check'. The argument
    'v' is the name of one of the first four functions in this script that you want to check. I make a different
    variable to make it harder for a user to figure out whats going on. You call this function in your code to check
    if any of the functions has been changed by the user.
  */
  self._doCodeCheck = function(v) {
      l = v;
      _doFunctionCheck(l);
  };
}())

También parece que la seguridad es realmente un problema y no hay manera de 'ocultar' la programación del lado del cliente. Una buena idea para mí es comprimir su código para que sea realmente difícil para cualquiera, incluido usted, el programador, leerlo y entenderlo. Hay un sitio al que puedes ir: http://javascriptcompressor.com / . (Este no es mi sitio, no te preocupes, no estoy haciendo publicidad.) Este es un sitio que te permitirá comprimir y ofuscar código Javascript de forma gratuita.

  1. Copie todo el código en el script anterior y péguelo en el área de texto superior en el javascriptcompressor.com page.
  2. Marque la casilla de verificación Codificar Base62, marque la casilla Reducir variables.
  3. Presione el botón Comprimir.
  4. Pegar y guardar todo en un .archivo js y agregarlo a su página en el encabezado de su página.
 5
Author: Steven Kapaun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-03 05:31:39

Claramente esto muestra la necesidad de una palabra clave const estandarizada entre navegadores.

Pero por ahora:

var myconst = value;

O

Object['myconst'] = value;

Ambos parecen suficientes y cualquier otra cosa es como disparar una mosca con una bazuca.

 5
Author: codemuncher,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-10 22:59:32

Utilizo const en lugar de var en mis scripts de Greasemonkey, pero es porque solo se ejecutarán en Firefox...
La convención de nombres puede ser de hecho el camino a seguir, también (¡Hago las dos cosas!).

 4
Author: PhiLho,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-24 22:49:33

En JavaScript mi práctica ha sido evitar constantes tanto como pueda y usar cadenas en su lugar. Los problemas con las constantes aparecen cuando desea exponer sus constantes al mundo exterior:

Por ejemplo, se podría implementar la siguiente API de fecha:

date.add(5, MyModule.Date.DAY).add(12, MyModule.Date.HOUR)

Pero es mucho más corto y más natural simplemente escribir:

date.add(5, "days").add(12, "hours")

De esta manera, los "días" y las "horas" realmente actúan como constantes, porque no se puede cambiar desde el exterior cuántos segundos representa "horas". Pero es fácil de sobrescribir MyModule.Date.HOUR.

Este tipo de enfoque también ayudará en la depuración. Si Firebug te dice action === 18 es bastante difícil averiguar lo que significa, pero cuando ves action === "save" entonces es inmediatamente claro.

 4
Author: Rene Saarsoo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-17 14:07:36

Bien, esto es feo, pero me da una constante en Firefox y Chromium, una constante inconstante (WTF?) en Safari y Opera, y una variable en IE.

Por supuesto eval() es malo, pero sin ella, IE lanza un error, evitando que los scripts se ejecuten.

Safari y Opera admiten la palabra clave const, pero puede cambiar el valor de const.

En este ejemplo, el código del lado del servidor está escribiendo JavaScript en la página, reemplazando {0} con un valor.

try{
    // i can haz const?
    eval("const FOO='{0}';");
    // for reals?
    var original=FOO;
    try{
        FOO='?NO!';
    }catch(err1){
        // no err from Firefox/Chrome - fails silently
        alert('err1 '+err1);
    }
    alert('const '+FOO);
    if(FOO=='?NO!'){
        // changed in Sf/Op - set back to original value
        FOO=original;
    }
}catch(err2){
    // IE fail
    alert('err2 '+err2);
    // set var (no var keyword - Chrome/Firefox complain about redefining const)
    FOO='{0}';
    alert('var '+FOO);
}
alert('FOO '+FOO);

¿Qué es ¿esto es bueno? No mucho, ya que no es cross-browser. En el mejor de los casos, tal vez un poco de tranquilidad de que al menos algunos navegadores no permitirán que bookmarklets o script de terceros modifiquen el valor.

Probado con Firefox 2, 3, 3.6, 4, Hierro 8, Cromo 10, 12, Opera 11, Safari 5, IE 6, 9.

 4
Author: Webveloper,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-28 04:39:48

Si vale la pena mencionarlo, puede definir constantes en angular usando $provide.constant()

angularApp.constant('YOUR_CONSTANT', 'value');
 4
Author: Muhammad Reda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-16 12:35:12

Una versión mejorada de La respuesta de Burke que te permite hacer CONFIG.MY_CONST en lugar de CONFIG.get('MY_CONST').

Requiere IE9+ o un navegador web real.

var CONFIG = (function() {
    var constants = {
        'MY_CONST': 1,
        'ANOTHER_CONST': 2
    };

    var result = {};
    for (var n in constants)
        if (constants.hasOwnProperty(n))
            Object.defineProperty(result, n, { value: constants[n] });

    return result;
}());

* Las propiedades son de solo lectura, solo si los valores iniciales son inmutables.

 4
Author: Şafak Gür,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:37

JavaScript ES6 (re-)introdujo el const palabra clave que es compatible con todos los principales navegadores.

Las variables declaradas a través de const no pueden ser re-declaradas o re-asignadas.

Aparte de eso, const se comporta similar a let.

Se comporta como se espera para los tipos de datos primitivos (Booleano, Null, Undefined, Number, String, Symbol):

const x = 1;
x = 2;
console.log(x); // 1 ...as expected, re-assigning fails

Atención: Sea consciente de las trampas con respecto a objetos:

const o = {x: 1};
o = {x: 2};
console.log(o); // {x: 1} ...as expected, re-assigning fails

o.x = 2;
console.log(o); // {x: 2} !!! const does not make objects immutable!

const a = [];
a = [1];
console.log(a); // 1 ...as expected, re-assigning fails

a.push(1);
console.log(a); // [1] !!! const does not make objects immutable

Si realmente necesita un objeto inmutable y absolutamente constante: Simplemente use const ALL_CAPS para aclarar su intención. Es una buena convención a seguir para todas las declaraciones const de todos modos, así que solo confíe en ella.

 4
Author: le_m,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-13 02:44:36

Otra alternativa es algo como:

var constants = {
      MY_CONSTANT : "myconstant",
      SOMETHING_ELSE : 123
    }
  , constantMap = new function ConstantMap() {};

for(var c in constants) {
  !function(cKey) {
    Object.defineProperty(constantMap, cKey, {
      enumerable : true,
      get : function(name) { return constants[cKey]; }
    })
  }(c);
}

Entonces simplemente: var foo = constantMap.MY_CONSTANT

Si fuera a constantMap.MY_CONSTANT = "bar" no tendría ningún efecto ya que estamos tratando de usar un operador de asignación con un getter, por lo tanto constantMap.MY_CONSTANT === "myconstant" seguiría siendo verdadero.

 3
Author: rounce,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-26 15:27:22

En Javascript ya existe constantes. Se define una constante como esta:

const name1 = value;

Esto no puede cambiar por reasignación.

 3
Author: Erik Lucio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-04 15:50:43

La palabra clave 'const' se propuso anteriormente y ahora se ha incluido oficialmente en ES6. Al usar la palabra clave const, puede pasar un valor / cadena que actuará como una cadena inmutable.

 3
Author: Ritumoni Sharma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-28 10:52:22

Introducir constantes en JavaScript es, en el mejor de los casos, un truco.

Una buena manera de hacer valores persistentes y globalmente accesibles en JavaScript sería declarar un objeto literal con algunas propiedades de "solo lectura" como esta:

            my={get constant1(){return "constant 1"},
                get constant2(){return "constant 2"},
                get constant3(){return "constant 3"},
                get constantN(){return "constant N"}
                }

Tendrá todas sus constantes agrupadas en un solo objeto accesorio "mi" donde podrá buscar sus valores almacenados o cualquier otra cosa que haya decidido poner allí para el caso. Ahora vamos a probar si funciona:

           my.constant1; >> "constant 1" 
           my.constant1 = "new constant 1";
           my.constant1; >> "constant 1" 

Como podemos ver, el " mi.la propiedad constant1 " ha conservado su valor original. Te has hecho algunas agradables constantes temporales 'verdes'...

Pero, por supuesto, esto solo lo protegerá de modificar, alterar, anular o vaciar accidentalmente el valor constante de su propiedad con un acceso directo como en el ejemplo dado.

De lo contrario, sigo pensando que las constantes son para maniquíes. Y sigo pensando que el intercambio de su gran libertad por un pequeño rincón de seguridad engañosa es el peor comercio posible.

 2
Author: Bill the Lizard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-03-20 02:45:25

Rhino.js implementa const además de lo mencionado anteriormente.

 2
Author: isomorphismes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-05 15:51:26