質問

があるので、使用の定数は、JavaScriptを?

ない場合には何の共通した慣習を指定するための変数として使用される定数?

役に立ちましたか?

解決

以降 ES2015, JavaScriptにはこ const:

const MY_CONSTANT = "some-value";

この作用 ほとんどすべてのブラウザ以外のIE8 9 10.一することが必要な場合もあります strictモード 有効になります。

利用できる var と条約のようにALL_CAPSる一定の値を改変することはできません対応させる必要がある場合には古いブラウザや携レガシーコード:

var MY_CONSTANT = "some-value";

他のヒント

ごうとして保護する変数に対変更?そのような場合は、利用できるモジュールのパターン:

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

このアプローチの値が変更されることはありません。でも、使用にはget()メソッドはCONFIG:(.

必要がない場合には厳重に保護する変数の値、そしてだけでな示唆されるように、使用コンベンションのすべてのキャップが入っています。

const キーワードは は、ECMAScript6案 それだけ楽しんsmatteringのブラウザをサポート: http://kangax.github.io/compat-table/es6/.の構文:

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

オブジェクトです。凍結.ができ 使用 const したい場合には、 constants 参考読み取り専用です。

IEは定数の例:

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

ECMAScript5は紹介 Object.defineProperty:

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

この 対応してすべてのブラウザ (IE≥9).

参照: オブジェクトです。definePropertyにES5?

とはできません。Firefoxを実装し const がんの家は来ない。


@ジョン ポイントが共通のネーミングの練習consts使用していたため年間のその他の言語の、あってはならない理由はなん使用します。もちろんな人ではないのだが、変数の値。:)

Mozillas MDN Web Docs を含む良い例についての解説 const.抜粋:

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

でも悲しいことIE9/10まだな const.の理由で 不条理:

それでは、IE9いconst?なので に、会社名、製品名は各社の商標れていない 支援します。いて合意 特徴としてではその利用 すべてのブラウザを推奨いたします。

...

最終的には、今思うと最高の 長期的な解決には 休暇で出待ち 標準化プロセスを行 コースです。

な実践できるので、その他のブラウザな実施を用い、正しく表してください?!も致していただくためのものです。基準の定義は、定数は定数:一度設定された、変更されます。

すべてのアイデア:毎機能を上書きすることができます(クロスサイト-スクリプティングなど)。その違いはありません var または function(){return}. const の定数です。

更新:IE11 対応 const:

IE11サポートの定義と、一般に用いられる特に新興ECMAScript6に準じめましょう, const, Map, Set, は、 WeakMap, など __proto__ 改善の相互運用性.

JavaScriptでは、私の好みでは機能を返す定数値です。

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


alert(MY_CONSTANT());

大きな機能を利用:

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

このアプローチで機能の代わりに通常の変数ですが、保証* さまざまな取り組みが変更に値します。

a = constant(10);

a(); // 10

b = constant(20);

b(); // 20

私個人の見どことなく心地よい、特に後慣れるこのパターンからのノックアウトゆる観察可能な要因.

*特記がない場合、誰が再定義した機能 constant 前まで

"新たな"オブジェクトのapiにいつものようになります:

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

この のMozilla MDN詳細目。でない最初のレベルの変数は、そのまま取り付けのオブジェクトがい範囲で、何もし替えで展開時を再現可能です。 this はとです。したがって、たとえば、このグローバル範囲ることを宣言致し擬似的に定数値のウィンドウであると思うんを宣言するグローバルvars不用意)

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

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

注意:課題を与えますの割り当てのコンソールの変数の値は変わりません

グループ定数への構造が可能な場合:

例では、現在のゲームプロジェクトでは、以下

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

担当:

var wildType = CONST_WILD_TYPES.REGULAR;

調査結果:

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

最近では私が使っていて、調査結果:

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

IE11で新しいES6標準と'const'ります。
上記の作品は以前のブラウザのようなIE8,IE9&IE10.

簡単に装備するスクリプトメカニズムのための定数で設定できるが変更されません。を変更していを生み出すエラーになります。

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

忘れIEを使用し const キーワードとなります。

まだありませんの正確なクロスブラウザの定義について教えてくださいできれば実現するための制御による範囲を変数として示したその他の応答となります。

ものご提案させていただきます使用の名前空間と区別するその他の変数.この機会を減少させ衝突を最小からその他の変数.

適切なnamespacingのように

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

なのでリスペクトしながら、することが発表されている iw_constant.name または iw_constant.age

またブロックの追加新しいキーまたは変化するエニーキーアンサー内iw_constant用オブジェクトです。凍結方法です。しかし、ではサポートされていないレガシーブラウザです。

ex:

Object.freeze(iw_constant);

古いブラウザで使用でき polyfill のための凍結方法です。


ま呼び出し機能はクロスブラウザの方法を定義する定数です。スコーピングおオブジェクト内で自己実行機能を返取得機能のご数 ex:

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

       };

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

//この値を取得し利用 iw_constant('name') または iw_constant('age')


**両の例でいうよう十分注意してください氏名の間隔でオブジェクトや機能な交換を通じてその他の図書館があります。場合はオブジェクトや機能そのものの異なる置換され一定数行)

が、指定された"定数"(だん実際の定数)オブジェクトリテラルを通過する with() 記述です。と思ったわけではないだろうか。次に例を示します。

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

過去において CONST 名前空間がないし全ての定数.再びオーバーヘッド。Sheesh.

今、私がい var MY_CONST = 'whatever';KISS.

私の意見(作品だ。

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

ぜひ使ってみてください。ものか-このオブジェクトが簡単に変更します。

みのもん

const a = 9;

私もまた問題です。後も模索しながら、その答えは、すべての対応により、誰もが安心して楽しいと思いまだ実行可能な解決策です。

その答えっくする機能を保持する定数.多くのユーザーの多くのフォーラムポストの機能に簡単にでき上が書いたユーザのクライアント側で行われます。私は、その不思議さに魅Keith Evetts'回答の定数オブジェクトではご利用いただけませんのもののみから機能を用いる。

いたこのソリューション:

を入れても内部の匿名の機能のように変数オブジェなど。変更はできませんのクライアント側で行われます。表のインターネットを"リアルの機能により他の機能、インターネットを"リアルの機能からです。いものと考えられている機能を利用確認機能が変更されているユーザのクライアント側で行われます。場の機能が変更された場合、変更後の使用変数としてくださ'を変更することはできません。

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

でもセキュリティは問題ありませんう'hide'お使いのプログラミングは、クライアント側で行われます。良いアイデアだと思い圧縮コードでは本当によく頑張ってくれ、誰でもあなたを含めて、プログラマーを読んで理解します。サイトがあります: http://javascriptcompressor.com/.(これは私のサイトで行くのが普通なんないんです。) このサイトにそのまま圧縮し蓑Javascriptコードを無料です。

  1. コピーのすべてのコードに上記のスクリプトおよびペーストのtextareaのjavascriptcompressor.com ページです。
  2. チェックをBase62エンコードのチェックボックスにチェックを縮小変数のチェックを入れて下さい。
  3. プレスの圧縮ボタンを押します。
  4. ペーストに保存してくださいすべてました。jsファイルに追加してくださいごのページの本のページです。

こ示の必要性は標準化されたクロスブラウザのconstキーワードとなります。

var myconst = value;

または

Object['myconst'] = value;

もう十分とそれ以外のものはすべてのように撮影フライとバズーカ.

使ってい const の代わりに var 私のGreasemonkeyスクリプトからのみ実行Firefox...
名前条約できるものもいます。).

JavaScriptの私が実践していを避けるようにして定数できるかぎり使用文字列です。問題の定数を表示したい場合なお定数の外の世界:

例えば、この実装は、下記の日程でサービスのAPI

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

ではより短いので、自然で簡単に書き:

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

このように"日"や"時間"も法のような定数が変更することができません外部から数秒"時間"を表します。でも、上書き MyModule.Date.HOUR.

このようなアプローチにも援助をデバッグしやすくなります。場合は開いているのがfirebugを教えてくれる action === 18 かかって走っていたりどのような意味が見えてきます action === "save" それはすぐに明らかでない。

大丈夫、これは美しくはないけれども、ちょっと一定でFirefoxおよびクロムは、変化を一定(作?) Safariやオペラ、および変数が打ち出されている。-

もちろんeval()が悪なので、スローエラー防止スクリプトから走っています。

サファリ、オペラのconstキーワードが の変更ができますconstの値.

この例では、サーバ側のコードを書くJavaScriptのページに置き換え{0}となります。

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

これは何ですかなかなクロスブラウザです。でもちょっと安心の少なくとも 一部の ブラウザでは、そんbookmarkletsまたは第三者のスクリプトの修正の値です。

試Firefox2,3,3.6,4,鉄8,Chrome10,12,オペラ11、Safari5、6、9日.

い場合には特筆に定義することができ定数 角度 を使用 $provide.constant()

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

改良版 バークからの回答 をまとめて見ることができるな CONFIG.MY_CONST の代わりに CONFIG.get('MY_CONST').

が必要でIE9+または本物のwebブラウザです。

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

*の特性を読み取り専用の場合のみ初期値は不変です。

JavaScript ES6(re-をご紹介いただき、インドネシア const キーワード には対応して すべての主要なブラウザ.

変数の宣言されたよ const きありがとうございます宣言した-再割り当てられます。

万谷塘文化公園などの見所も const 動作と類似 let.

いとして振る舞うと考えられているプリミティブデータ型(Boolean、Nullの場合、定義されていません、数字、文字列、記号):

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

注意: この落とし穴につオブジェクト

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

なので、しばらく日本には必要不変の絶対的定数オブジェクト:使おう const ALL_CAPS ご意思が明らかでない。良い条約に従う全ての const 宣言はともかく、なだけに頼ります。

他のインタビューを受けたことがあのようなもの:

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

その後で: var foo = constantMap.MY_CONSTANT

した場合 constantMap.MY_CONSTANT = "bar" してしまうだろうとして使用する代入演算子を取得メソッドを持つこ constantMap.MY_CONSTANT === "myconstant" もう。

Javascriptがすでに存在する 定数.を定義する定数のようになります:

const name1 = value;

この変更ができないよ再びご用意します。

キーワード'const'を提案した前までに正式に含まれES6.のconstキーワードとすることができます値/文字列として、変更不能な文字列になります。

定数の導入に当サイトでは、以下のブラウザでは、hack.

エクスペディアの恒久的ではなく、世界的にアクセスの値がJavaScriptが宣言するオブジェクトリテラルの一部では"読み取り専用"とまっていただいた皆様ありがとうこ

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

いすべて定数をグルーピング一つでシングル"私の"クオブジェクトが使用されてきたこのお値が格納されただけあうことについて決議しましたのである。今ましょう試験場での作品:

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

こと、"my.constant1"プロパティが保存された元の値です。いつまで経っても自分であるグリーン仮定数の...

もちろん、こみ上保安庁からの偶発的に改変、改変、じ、または空において、資産を一定値に直接アクセスして、指定された例です。

その他たなければならないと思いる定数はダミー.やたなければならないと思いるの交換をご自由度の小さなコーナーの不正なセキュリティが最悪の貿易が可能です。

Rhino.jsconst るもののほかった。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top