Domanda

C'è un modo per usare le costanti in JavaScript?

In caso contrario, qual è la pratica comune per specificare le variabili che vengono utilizzate come costanti?

È stato utile?

Soluzione

Poiché ES2015 , JavaScript ha la nozione di const :

const MY_CONSTANT = "some-value";

Funzionerà in praticamente tutti i browser tranne IE 8, 9 e 10 . Alcuni potrebbero anche aver bisogno della modalità rigorosa abilitata.

Puoi usare var con convenzioni come ALL_CAPS per mostrare che alcuni valori non devono essere modificati se devi supportare browser più vecchi o stai lavorando con un codice legacy:

var MY_CONSTANT = "some-value";

Altri suggerimenti

Stai cercando di proteggere le variabili dalle modifiche? In tal caso, puoi utilizzare un modello di modulo:

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 questo approccio, i valori non possono essere modificati. Ma devi usare il metodo get () su CONFIG :(.

Se non è necessario proteggere rigorosamente il valore delle variabili, fare semplicemente come suggerito e utilizzare una convenzione di TUTTI MAIUSCOLI.

La parola chiave const è in la bozza ECMAScript 6 ma finora gode solo di un'infarinatura del supporto del browser: http: // kangax. github.io/compat-table/es6/. La sintassi è:

const CONSTANT_NAME = 0;
"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

Vedi Object.freeze . Puoi utilizzare const se vuoi creare il riferimento costanti anche di sola lettura.

IE supporta costanti, una specie di, ad esempio:

<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>

ECMAScript 5 introduce Object.defineProperty :

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

È supportato in tutti i browser moderni (così come IE = 9).

Vedi anche: Object.defineProperty in ES5?

No, non in generale. Firefox implementa const ma so che IE no.


@John indica una pratica di denominazione comune per i consoli che è stata utilizzata per anni in altre lingue, non vedo alcun motivo per non poterlo usare. Ovviamente ciò non significa che qualcuno non scriverà comunque sul valore della variabile. :)

Mozillas MDN Web Docs contengono buoni esempi e spiegazioni su const . Estratto:

// 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;

Ma è triste che IE9 / 10 non supporti ancora const . E il motivo è assurdo :

  

Quindi, cosa sta facendo IE9 con const? Così   lontano, la nostra decisione è stata di non farlo   supportalo. Non è ancora un consenso   caratteristica in quanto non è mai stata disponibile   su tutti i browser.

     

...

     

Alla fine, sembra il migliore   soluzione a lungo termine per il web è   lasciarlo fuori e aspettare   processi di standardizzazione per eseguire il loro   corso.

Non lo implementano perché altri browser non lo hanno implementato correttamente ?! Hai paura di renderlo migliore? Definizioni standard o no, una costante è una costante: impostata una volta, mai modificata.

E a tutte le idee: ogni funzione può essere sovrascritta (XSS ecc.). Quindi non vi è alcuna differenza nella funzione var o () {return} . const è l'unica costante reale.

Aggiornamento: IE11 supporta const :

  

IE11 include il supporto per le funzionalità ben definite e comunemente utilizzate dello standard emergente ECMAScript 6 tra cui let, const , Map , < code> Set e WeakMap , nonché __proto__ per una migliore interoperabilità.

In JavaScript, la mia preferenza è usare le funzioni per restituire valori costanti.

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


alert(MY_CONSTANT());

Se non ti dispiace usare le funzioni:

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

Questo approccio offre funzioni anziché variabili regolari, ma garantisce * che nessuno può modificare il valore una volta impostato.

a = constant(10);

a(); // 10

b = constant(20);

b(); // 20

Personalmente lo trovo piuttosto piacevole, specialmente dopo essermi abituato a questo modello da osservabili knockout.

* A meno che qualcuno non abbia ridefinito la funzione costante prima di chiamarla

con il " nuovo " Oggetto api puoi fare qualcosa del genere:

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

dai un'occhiata a this su Mozilla MDN per ulteriori informazioni specifiche. Non è una variabile di primo livello, poiché è collegata a un oggetto, ma se si dispone di un ambito, qualsiasi cosa, è possibile collegarlo a quello. Anche this dovrebbe funzionare. Quindi, ad esempio, farlo nell'ambito globale dichiarerà un valore pseudo costante sulla finestra (che è una pessima idea, non dovresti dichiarare negativamente i varchi globali)

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

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

nota: l'assegnazione restituirà il valore assegnato nella console, ma il valore della variabile non cambierà

Raggruppa le costanti in strutture ove possibile:

Esempio, nel mio attuale progetto di gioco, ho usato di seguito:

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

Assegnazione:

var wildType = CONST_WILD_TYPES.REGULAR;

: bilanciamento

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

Più recentemente sto usando, per confronto:

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

IE11 è con il nuovo standard ES6 che ha la dichiarazione 'const'.
Sopra funziona nei browser precedenti come IE8, IE9 & amp; IE10.

Puoi facilmente dotare il tuo script di un meccanismo per costanti che può essere impostato ma non modificato. Un tentativo di modificarli genererà un errore.

/* 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  

Dimentica IE e usa la parola chiave const .

Eppure non esiste un modo predefinito per eseguire esattamente il browser incrociato, puoi ottenerlo controllando l'ambito delle variabili come mostrato in altre risposte.

Ma suggerirò di usare lo spazio dei nomi per distinguere dalle altre variabili. questo ridurrà al minimo le possibilità di collisione da altre variabili.

Corretto spazio dei nomi come

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

quindi durante l'utilizzo sarà iw_constant.name o iw_constant.age

Puoi anche bloccare l'aggiunta di qualsiasi nuova chiave o la modifica di qualsiasi chiave all'interno di iw_constant usando il metodo Object.freeze. Tuttavia, non è supportato sul browser legacy.

ex:

Object.freeze(iw_constant);

Per i browser meno recenti puoi utilizzare polyfill per il metodo di blocco.


Se sei d'accordo con la funzione di chiamata, il modo migliore per definire la costante è il seguente browser incrociato. Scoping dell'oggetto all'interno di una funzione autoeseguente e restituzione di una funzione get per le costanti es:

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

       };

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

// per ottenere il valore utilizzare iw_constant ('name') o iw_constant('age')


** In entrambi gli esempi devi stare molto attento alla spaziatura dei nomi in modo che l'oggetto o la funzione non vengano sostituiti con altre librerie (se l'oggetto o la funzione stessa verranno sostituiti, andrà tutta la tua costante)

Per un po 'ho specificato " costanti " (che in realtà non erano ancora costanti) nei letterali degli oggetti passati a con istruzioni () . Ho pensato che fosse così intelligente. Ecco un esempio:

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

In passato, ho anche creato uno spazio dei nomi CONST in cui avrei inserito tutte le mie costanti. Ancora una volta, con il sovraccarico. Sheesh.

Ora, faccio solo var MY_CONST = 'qualunque cosa'; a KISS .

La mia opinione (funziona solo con oggetti).

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

Prova! Ma comprendi: questo è un oggetto, ma non una semplice variabile.

Prova anche solo:

const a = 9;

Anch'io ho avuto un problema con questo. E dopo un po 'di tempo cercando la risposta e guardando tutte le risposte di tutti, penso di aver trovato una soluzione praticabile a questo.

Sembra che la maggior parte delle risposte che ho incontrato stia usando le funzioni per contenere le costanti. Come molti degli utenti dei MOLTI forum pubblicano, le funzioni possono essere facilmente sovrascritte dagli utenti sul lato client. Sono stato incuriosito dalla risposta di Keith Evetts secondo cui l'oggetto delle costanti non è accessibile dall'esterno, ma solo dalle funzioni all'interno.

Quindi ho trovato questa soluzione:

Metti tutto all'interno di una funzione anonima in modo tale che variabili, oggetti, ecc. non possano essere modificati dal lato client. Inoltre nascondi le funzioni "reali" facendo in modo che altre funzioni chiamino le funzioni "reali" dall'interno. Ho anche pensato di utilizzare le funzioni per verificare se una funzione è stata modificata da un utente sul lato client. Se le funzioni sono state modificate, modificale di nuovo usando le variabili "protette" all'interno e che non possono essere modificate.

/*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);
  };
}())

Sembra anche che la sicurezza sia davvero un problema e non c'è modo di "nascondere" la programmazione dal lato client. Una buona idea per me è comprimere il codice in modo che sia davvero difficile per chiunque, incluso te, il programmatore, leggerlo e comprenderlo. È possibile visitare un sito: http://javascriptcompressor.com/ . (Questo non è il mio sito, non ti preoccupare, non sto facendo pubblicità.) Questo è un sito che ti permetterà di comprimere e offuscare il codice Javascript gratuitamente.

  1. Copia tutto il codice nello script sopra e incollalo nella textarea superiore nella pagina javascriptcompressor.com.
  2. Seleziona la casella di controllo Codifica Base62, seleziona la casella Riduci variabili.
  3. Premi il pulsante Comprimi.
  4. Incolla e salva tutto in un file .js e aggiungilo alla tua pagina in testa alla tua pagina.

Chiaramente questo dimostra la necessità di una parola chiave const standardizzata su più browser.

Ma per ora:

var myconst = value;

o

Object['myconst'] = value;

Entrambi sembrano sufficienti e qualsiasi altra cosa è come sparare a una mosca con un bazooka.

Uso const invece di var nei miei script Greasemonkey, ma è perché funzioneranno solo su Firefox ...
Anche la convenzione dei nomi può davvero essere la strada da percorrere (faccio entrambe le cose!).

In JavaScript la mia pratica è stata quella di evitare le costanti il ??più possibile e usare invece stringhe. I problemi con le costanti compaiono quando vuoi esporre le tue costanti al mondo esterno:

Ad esempio, è possibile implementare la seguente API Data:

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

Ma è molto più breve e naturale scrivere semplicemente:

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

In questo modo " giorni " e "ore" si comportano davvero come costanti, perché non puoi cambiare dall'esterno quanti secondi " ore " rappresenta. Ma è facile sovrascrivere MyModule.Date.HOUR .

Questo tipo di approccio aiuterà anche nel debug. Se Firebug ti dice action === 18 è abbastanza difficile capire cosa significhi, ma quando vedi action === " save " è immediatamente chiaro.

Va ??bene, è brutto, ma mi dà una costante in Firefox e Chromium, una costante incostante (WTF?) in Safari e Opera e una variabile in IE.

Ovviamente eval () è malvagio, ma senza di esso, IE genera un errore, impedendo l'esecuzione degli script.

Safari e Opera supportano la parola chiave const, ma puoi cambiare il valore della const .

In questo esempio, il codice lato server sta scrivendo JavaScript nella pagina, sostituendo {0} con un valore.

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);

A cosa serve questo? Non molto, dal momento che non è cross-browser. Nella migliore delle ipotesi, forse un po 'di tranquillità che almeno alcuni browser non consentiranno ai bookmarklet o agli script di terze parti di modificare il valore.

Testato con Firefox 2, 3, 3.6, 4, Iron 8, Chrome 10, 12, Opera 11, Safari 5, IE 6, 9.

Se vale la pena menzionare, puoi definire le costanti in angolare usando $ fornire.constant ()

angularApp.constant('YOUR_CONSTANT', 'value');

Una versione migliorata di la risposta di Burke che ti consente di eseguire CONFIG.MY_CONST anziché < code> CONFIG.get ( 'MY_CONST') .

Richiede IE9 + o un browser Web reale.

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;
}());

* Le proprietà sono di sola lettura, solo se i valori iniziali sono immutabili.

JavaScript ES6 (ri) ha introdotto la const parola chiave supportata in tutti i principali browser .

  

Le variabili dichiarate tramite const non possono essere dichiarate o riassegnate.

A parte ciò, const si comporta in modo simile a lasciare che .

Si comporta come previsto per i tipi di dati primitivi (booleano, null, indefinito, numero, stringa, simbolo):

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

Attenzione: fai attenzione alle insidie ??riguardanti gli oggetti:

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

Se hai davvero bisogno di un oggetto immutabile e assolutamente costante: usa const ALL_CAPS per chiarire le tue intenzioni. È comunque una buona convenzione da seguire per tutte le dichiarazioni const , quindi fai affidamento su di essa.

Un'altra alternativa è qualcosa di simile:

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);
}

Quindi semplicemente: var foo = constantMap.MY_CONSTANT

Se dovessi constantMap.MY_CONSTANT = " bar " non avrebbe alcun effetto poiché stiamo cercando di utilizzare un operatore di assegnazione con un getter, quindi constantMap.MY_CONSTANT == = " myconstant " rimarrebbe vero.

in Javascript esiste già costanti . Definisci una costante come questa:

const name1 = value;

Questo non può cambiare attraverso la riassegnazione.

La parola chiave 'const' è stata proposta in precedenza e ora è stata ufficialmente inclusa in ES6. Usando la parola chiave const, puoi passare un valore / stringa che fungerà da stringa immutabile.

L'introduzione di costanti in JavaScript è nella migliore delle ipotesi un trucco.

Un buon modo per rendere persistenti e accessibili globalmente valori in JavaScript sarebbe dichiarare un oggetto letterale con alcuni "solo lettura"; proprietà come questa:

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

avrai tutte le tue costanti raggruppate in un unico " my " oggetto accessorio in cui puoi cercare i valori memorizzati o qualsiasi altra cosa che potresti aver deciso di mettere lì per quella materia. Ora proviamo se funziona:

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

Come possiamo vedere, il " my.constant1 " la proprietà ha conservato il suo valore originale. Ti sei fatto delle belle costanti temporanee "verdi" ...

Ma ovviamente questo ti proteggerà solo dalla modifica, dall'alterazione, dall'annullamento o dallo svuotamento accidentale del valore della costante della tua proprietà con un accesso diretto come nell'esempio dato.

Altrimenti penso ancora che le costanti siano per i manichini. E penso ancora che scambiare la tua grande libertà con un piccolo angolo di sicurezza ingannevole sia il peggior commercio possibile.

Rhino.js implementa const oltre a quanto menzionato sopra.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top