Frage

Gibt es eine Möglichkeit Konstanten in JavaScript zu benutzen?

Wenn nicht, was die gängige Praxis ist Variablen für die Angabe, die als Konstanten verwendet werden?

War es hilfreich?

Lösung

Da ES2015 hat JavaScript eine Vorstellung von const :

const MY_CONSTANT = "some-value";

Dies wird in rel="noreferrer">. Einige müssen auch Strict-Modus aktiviert.

Sie können var mit Konventionen wie ALL_CAPS verwenden zu zeigen, dass bestimmte Werte nicht geändert werden sollen, wenn Sie älteren Browser unterstützen müssen oder arbeiten mit Legacy-Code:

var MY_CONSTANT = "some-value";

Andere Tipps

Versuchen Sie, die Variablen vor Veränderungen zu schützen? Wenn ja, dann können Sie ein Modul Muster verwenden:

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

Mit diesem Ansatz können die Werte nicht verändert werden. Aber, müssen Sie die Methode get () auf CONFIG verwenden. (

Wenn Sie nicht brauchen, streng an den Variablen Wert zu schützen, dann tun, wie vorgeschlagen und eine Konvention von ALL CAPS verwenden.

Das const Schlüsselwort ist in der ECMAScript 6 Entwurf aber es somit bisher nur genießt ein paar Brocken Browser-Unterstützung: http://kangax.github.io/compat-table / es6 / . Die Syntax lautet:

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

Siehe Object.freeze . Sie können href="https://stackoverflow.com/a/687457/822138"> verwenden const constants Referenzschreibgeschützt als auch machen wollen.

IE tut Unterstützung Konstanten, Art, z.

<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 einführt Object.defineProperty :

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

Es ist in jedem modernen Browser unterstützt (wie auch IE ≥ 9).

Siehe auch: Object.defineProperty in ES5

Nein, nicht im Allgemeinen. Firefox implementiert const aber ich weiß, IE nicht.


@John Punkte auf einer gemeinsamen Benennungspraxis für consts, die seit Jahren verwendet wurde, in anderen Sprachen, sehe ich keinen Grund, warum Sie nicht, dass nutzen könnten. Natürlich, dass jemand bedeutet nicht, wird ohnehin nicht den Wert der Variablen überschreiben. :)

Mozillas MDN Web Docs enthalten gute Beispiele und Erklärungen zu const. Auszug:

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

Aber es ist traurig, dass IE9 / 10 noch nicht const unterstützt. Und der Grund, es ist absurd :

  

Also, was ist IE9 mit konst tun? Damit   Bis jetzt hat unsere Entscheidung nicht gewesen   unterstütze es. Es ist noch kein Konsens   Funktion, da sie noch nie zur Verfügung   auf allen Browsern.

     

...

     

Am Ende scheint es, wie die besten   langfristige Lösung für das Web ist zu   lassen Sie es aus und warten,   Standardisierungsprozesse zu laufen ihre   Natürlich.

Sie implementiere es nicht, weil andere Browser es richtig nicht implementieren ?! Zu viel Angst, es besser zu machen? Standards Definitionen oder nicht, eine Konstante ist eine Konstante. Einmal gesetzt, nie geändert

Und an alle Ideen: Jede Funktion überschrieben werden können (XSS etc.). So gibt es keinen Unterschied in var oder function(){return}. const ist die einzige wirkliche Konstante ist.

Update: IE11 unterstützt const:

  

IE11 bietet Unterstützung für die gut definiert und häufig verwendete Funktionen des neuen ECMAScript 6 Standard einschließlich let, const , Map, Set und WeakMap sowie __proto__ für eine verbesserte Interoperabilität.

Sie JavaScript, um meine Präferenz ist es, Funktionen zu verwenden konstanten Werten zurückzukehren.

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


alert(MY_CONSTANT());

Wenn Sie nichts dagegen haben Funktionen:

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

Dieser Ansatz gibt Ihnen Funktionen anstelle von normalen Variablen, aber es garantiert * , dass niemand kann den Wert ändern, sobald es festgelegt wird.

a = constant(10);

a(); // 10

b = constant(20);

b(); // 20

ich diese persönlich finde eher angenehm, besonders nach dem von Knockout Observablen dieses Muster daran gewöhnt zu haben.

* Es sei denn, jemand die Funktion constant neu definiert, bevor Sie es genannt

mit dem „neuen“ Objekt api Sie etwas tun können:

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

zu sehen dieser auf dem Mozilla MDN für mehr Besonderheiten. Es ist nicht eine erste Ebene variabel, da es an einem Objekt angebracht ist, aber wenn Sie einen Bereich, etwas haben, können Sie es zu, dass befestigen. this sollte auch funktionieren. So zum Beispiel die im globalen Bereich tun wird eine Pseudo konstanten Wert auf dem Fenster deklariert

(das ist eine wirklich schlechte Idee ist, sollten Sie globale Vars nachlässig nicht erklären)
Object.defineProperty(this, 'constant', {
  enumerable: true, 
  writable: false, 
  value: 7, 
  configurable: false
});

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

Hinweis: Zuordnung geben Sie den zugewiesenen Wert in der Konsole zurück, aber den Wert der Variablen wird sich nicht ändern

Gruppen-Konstanten in Strukturen, in denen möglich:

Beispiel, in meinem aktuellen Spiel-Projekt, ich habe unten verwendet:

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

Zuordnung:

var wildType = CONST_WILD_TYPES.REGULAR;

Vergleich:

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

In jüngerer Zeit verwende ich, zum Vergleich:

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

IE11 ist mit neuem ES6-Standard, der 'const' Erklärung hat.
Oben genannte Arbeiten in früheren Browsern wie IE8, IE9 und IE10.

Sie können das Skript mit einem Mechanismus für die Konstanten leicht auszustatten, die eingestellt werden können, aber nicht verändert werden. Ein Versuch, zu verändern, sie wird einen Fehler erzeugen.

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

Vergessen Sie IE verwenden, const Schlüsselwort.

Und doch gibt es keine genaue Cross-Browser vordefinierte Art und Weise, es zu tun, können Sie es erreichen, indem sie den Umfang der Variablen zu steuern, wie auf anderen Antworten zeigten.

Aber ich werde vorschlagen Namensraum zu verwenden, um von anderen Variablen zu unterscheiden. Dadurch wird die Wahrscheinlichkeit einer Kollision auf ein Minimum von anderen Variablen reduzieren.

Proper Namespacing wie

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

so bei der Verwendung wird es iw_constant.name oder iw_constant.age

wird Block

Sie können auch jeden neuen Schlüssel oder das Ändern einer beliebigen Taste innerhalb iw_constant mit Object.freeze Methode hinzufügen. Doch es ist nicht auf Legacy-Browser nicht unterstützt.

ex:

Object.freeze(iw_constant);

Für älteren Browser können Sie verwenden polyfill für Freeze-Verfahren.


Wenn Sie sind ok mit Aufruf Funktion finden Sie beste Cross-Browser-Art und Weise konstant zu definieren. Scoping Ihr Objekt innerhalb einer Selbst Funktion ausführen und eine get-Funktion für Ihre Konstanten Rückkehr Ex:

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

       };

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

// den Wert Verwendung erhalten iw_constant('name') oder iw_constant('age')


** Sowohl Beispiel müssen Sie auf dem Namen Abstand sehr vorsichtig sein, so dass das Objekt oder die Funktion nicht durch andere Bibliothek ersetzt werden. (Wenn das Objekt oder die Funktion selbst wil Ihre ganze Konstante geht ersetzt werden)

Für eine Weile I der „Konstanten“ (was immer noch nicht wirklich Konstanten waren) in Objektliterale durchlaufen Aussagen with(). Ich dachte, es war, so clever. Hier ein Beispiel:

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

In der Vergangenheit habe ich auch einen CONST Namensraum geschaffen, in dem ich alle meine Konstanten setzen würde. Wieder mit dem Overhead. Meine Güte.

Nun, ich var MY_CONST = 'whatever'; nur href="http://en.wikipedia.org/wiki/KISS_principle" rel="noreferrer"> KISS

Meine Meinung (funktioniert nur mit Objekten).

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

Versuchen Sie es! Aber verstehen -. Diese Aufgabe ist, aber nicht einfache Variable

Versuchen Sie auch nur:

const a = 9;

Auch ich habe ein Problem damit hatte. Und nach einer Weile nach der Antwort suchen und Blick auf all die Antworten von allen, ich glaube, ich habe eine brauchbare Lösung dieses Problems kommen.

Es scheint, dass die meisten der Antworten, die ich gekommen bin über Funktionen unter Verwendung der Konstanten zu halten. Da viele der Nutzer von den vielen Foren über Post können die Funktionen von Benutzern problemlos auf der Client-Seite geschrieben zu Ende sein. Ich war fasziniert von Keith Evetts' Antwort, dass die Konstanten Objekt kann nicht von außen zugegriffen werden, sondern nur von den Funktionen auf der Innenseite.

So kam ich mit dieser Lösung:

Setzen Sie alles in einer anonymen Funktion, so dass Art und Weise, die Variablen, Objekte, usw. können nicht von der Client-Seite geändert werden. Auch blenden Sie die ‚echten‘ Funktionen mit anderen Funktionen, um die ‚echten‘ Funktionen von innen nennen. Ich dachte auch Funktionen der Verwendung zu überprüfen, ob eine Funktion von einem Benutzer auf der Client-Seite geändert wurde. Wenn die Funktionen geändert haben, ändern Sie sie mit Variablen zurück, die ‚geschützt‘ sind auf der Innenseite und kann nicht geändert werden kann.

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

Es scheint auch, dass die Sicherheit ist wirklich ein Problem, und es ist nicht Art und Weise zu ‚verstecken‘ Programmieren Sie von der Client-Seite. Eine gute Idee für mich ist, den Code zu komprimieren, so dass es wirklich schwer ist für jedermann, auch Sie, den Programmierer, es zu lesen und zu verstehen. Es gibt eine Website, die Sie gehen können: http://javascriptcompressor.com/ . (Dies ist nicht meine Seite, keine Sorge ich bin keine Werbung.) Dies ist eine Website, die Sie komprimieren und verschleiern Javascript-Code kostenlos lassen.

  1. Kopieren Sie den gesamten Code in dem obigen Skript und es in das Top-Textfeld auf der javascriptcompressor.com Seite einfügen.
  2. Überprüfen Sie die Base62 kodieren Checkbox, überprüfen Sie die Variablen Checkbox verkleinern.
  3. Drücken Sie die Taste Komprimieren.
  4. Einfügen und das alles in einer JS-Datei speichern und auf Ihre Seite in dem Kopf Ihrer Seite hinzufügen.

Deutlich zeigt dies die Notwendigkeit eines standardisierten Cross-Browser-Schlüsselwort const.

Aber jetzt:

var myconst = value;

oder

Object['myconst'] = value;

Beide scheinen ausreichend und alles andere ist wie eine Fliege mit einer Panzerfaust schießen.

Ich verwende const statt var in meinem Grease Skripte, aber es ist, weil sie nur auf Firefox läuft ...
Namenskonvention kann in der Tat der Weg zu gehen, auch (ich beides tun!).

In JavaScript meiner Praxis war Konstanten so viel zu vermeiden, wie ich kann und Strings stattdessen verwenden. Probleme mit Konstanten angezeigt, wenn Sie Ihre Konstanten nach außen verfügbar machen möchten:

Zum Beispiel könnte man das folgende Datum API implementieren:

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

Aber es ist viel kürzer und natürlich einfach schreiben:

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

Auf diese Weise „Tage“ und „Stunden“ wirklich wie Konstanten handeln, weil man nicht von außen, wie viele Sekunden „Stunden“ repräsentiert ändern kann. Aber es ist einfach MyModule.Date.HOUR zu überschreiben.

Diese Art von Ansatz wird auch bei der Fehlersuche unterstützen. Wenn Firebug sagt action === 18 Sie es ziemlich schwer ist, herauszufinden, was es bedeutet, aber wenn man action === "save" sehen, dann ist es sofort klar.

Okay, das ist hässlich, aber es gibt mir eine Konstante in Firefox und Chromium, nicht konstanten Konstante (WTF?) In Safari und Opera, und eine Variable im Internet Explorer.

Natürlich eval () ist böse, aber ohne sie, wirft IE einen Fehler, Skripte laufen zu verhindern.

Safari und Opera unterstützen das Schlüsselwort const, aber Sie den Wert des const ändern .

In diesem Beispiel serverseitigen Code ist JavaScript auf der Seite schreiben, ersetzt {0} mit einem Wert.

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

Was ist das gut? Nicht viel, da es nicht Cross-Browser. Am besten, vielleicht ein wenig Sicherheit, dass zumindest einige Browser werden nicht Bookmarklets oder Fremd Skript lassen den Wert ändern.

Getestet mit dem folgenden 2, 3, 3,6, 4, 8 Eisen, Chrom-10, 12, Opera 11, Safari 5, IE 6, 9.

Wenn es erwähnenswert ist, können Sie Konstanten in rel="nofollow"> mit $provide.constant()

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

Eine verbesserte Version von Burkes Antwort , mit dem Sie statt CONFIG.MY_CONST do CONFIG.get('MY_CONST').

Es erfordert IE9 + oder ein echter Web-Browser.

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

* Die Eigenschaften sind schreibgeschützt, nur dann, wenn die Anfangswerte sind unveränderlich.

JavaScript ES6 (Wieder-) eingeführt, um das const Schlüsselwort , die in alle gängigen Browsern .

  

Variablen über const deklariert sind, können nicht erneut deklariert oder neu zugewiesen werden.

Abgesehen davon verhält sich ähnlich wie const let .

Es verhält sich wie erwartet für primitive Datentypen (Boolean, Null, nicht definierte Nummer, String, Symbol):

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

Achtung: Achten Sie auf die Gefahren in Bezug auf Objekte:

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

Wenn Sie wirklich ein unveränderliches und absolut konstantes Objekt benötigen: Verwenden Sie einfach const ALL_CAPS Ihre Absicht klar zu machen. Es ist eine gute Konvention für alle const Erklärungen ohnehin zu folgen, so dass nur auf sie verlassen.

Eine weitere Alternative ist so etwas wie:

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

Dann einfach: var foo = constantMap.MY_CONSTANT

Wenn Sie sind es constantMap.MY_CONSTANT = "bar" hätte keine Auswirkung hat, wie wir versuchen, einen Zuweisungsoperator mit einem Getter zu verwenden, daher würde constantMap.MY_CONSTANT === "myconstant" treu bleiben.

in Javascript ist bereits vorhanden Konstanten . Sie definieren eine Konstante wie folgt aus:

const name1 = value;

Das kann nicht durch Neuzuordnung ändern.

Das Schlüsselwort ‚const‘ wurde früher vorgeschlagen, und jetzt ist es in ES6 offiziell aufgenommen wurde. Durch das Schlüsselwort const verwenden, können Sie einen Wert / string übergeben, die als unveränderliche Zeichenfolge handeln wird.

Konstanten in JavaScript Einführung ist bestenfalls ein Hack.

Ein schöner Weg, um persistente und global zugängliche Werte in JavaScript würde einen Objektliteral mit einigen „read-only“ Eigenschaften wie diese wird erklärt:

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

Sie haben alle Ihre Konstanten zusammengefasst in einem einzigen „my“ Zubehörobjekt, in dem Sie Ihre gespeicherten Werte oder was immer Sie es für diese Angelegenheit zu setzen beschlossen kann aussehen kann. Nun wollen wir testen, ob es funktioniert:

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

Wie wir sehen können, hat sich die „my.constant1“ Eigenschaft seinen ursprünglichen Wert bewahrt. Sie haben sich aus ein paar schöne ‚grüne‘ temporäre Konstanten ...

Aber natürlich wird dies nur Schutz vor versehentlichen Ändern, Ändern, zunichte gemacht oder Ihre Eigenschaft konstanten Wert mit einem direkten Zugriff wie in dem gegebenen Beispiel zu entleeren.

Ansonsten denke ich immer noch, dass Konstanten für Dummies sind. Und ich denke immer noch, dass Ihre große Freiheit für eine kleine Ecke trügerisch Sicherheit Austausch den schlimmsten Handel möglich ist.

Rhino.js implementiert const zusätzlich zu dem, was oben erwähnt wurde.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top