Programing

JavaScript에 상수가 있습니까?

lottogame 2020. 9. 27. 12:39
반응형

JavaScript에 상수가 있습니까?


JavaScript에서 상수를 사용하는 방법이 있습니까?

그렇지 않다면 상수로 사용되는 변수를 지정하는 일반적인 관행은 무엇입니까?


ES2015 이후 JavaScript는 다음과 같은 개념을 가지고 있습니다 const.

const MY_CONSTANT = "some-value";

이것은 IE 8, 9 및 10을 제외한 거의 모든 브라우저 에서 작동 합니다. 일부는 엄격 모드를 활성화 해야 할 수도 있습니다 .

varALL_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

이 방법을 사용하면 값을 수정할 수 없습니다. 그러나 CONFIG에서 get () 메소드를 사용해야합니다.

변수 값을 엄격하게 보호 할 필요가없는 경우 제안 된대로 수행하고 ALL CAPS 규칙을 사용하십시오.


const키워드에 ECMA 스크립트 (6) 초안 하지만 지금까지 유일한 브라우저 지원의 겉 핥기 즐깁니다 : 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

Object.freeze를 참조하십시오 . 참조를 읽기 전용으로 만들려는 경우에도 사용할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>

ECMAScript 5는 다음을 소개합니다 Object.defineProperty.

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

그것은있어 모든 현대적인 브라우저에서 지원 (물론 IE ≥ 9).

참조 : ES5의 Object.defineProperty?


아니, 일반적이지 않습니다. Firefox는 구현 const하지만 IE는 구현 하지 않습니다.


@ 존 다른 언어로 년 동안 사용되어왔다 consts에 대한 일반적인 명명 연습 점, 나는 당신이 그것을 사용할 수없는 이유가 없습니다. 물론 그렇다고해서 누군가 변수의 값을 덮어 쓰지 않을 것이라는 의미는 아닙니다. :)


Mozillas MDN 웹 문서 에는에 대한 좋은 예와 설명이 포함되어 있습니다 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로 무엇을하고 있습니까? 지금까지 우리의 결정은 그것을 지원하지 않는 것이 었습니다. 모든 브라우저에서 사용할 수 없었기 때문에 아직 합의 기능이 아닙니다.

...

결국 웹을위한 가장 좋은 장기적인 솔루션은 웹을 그대로두고 표준화 프로세스가 진행될 때까지 기다리는 것 같습니다.

다른 브라우저에서 제대로 구현하지 않았기 때문에 구현하지 않습니까?! 더 나아지게 만드는 것이 너무 두려워? 표준 정의 여부에 관계없이 상수는 상수입니다. 한 번 설정하면 변경되지 않습니다.

그리고 모든 아이디어 : 모든 기능을 덮어 쓸 수 있습니다 (XSS 등). 따라서 var또는 에는 차이가 없습니다 function(){return}. const유일한 실제 상수입니다.

업데이트 : IE11 const 다음을 지원합니다 .

IE11은하자를 포함한 신흥 인 ECMAScript 6 표준의 잘 정의 일반적으로 사용되는 기능에 대한 지원이 포함 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당신이 호출하기 전에 누군가 함수 재정의하지 않는 한


"new"Object api를 사용하면 다음과 같이 할 수 있습니다.

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

한 번 봐 가지고 더 구체적인 내용 모질라 MDN에 있습니다. 개체에 연결되어 있기 때문에 첫 번째 수준 변수가 아니지만 범위가 있으면 여기에 연결할 수 있습니다. this잘 작동합니다. 예를 들어 전역 범위에서이 작업을 수행하면 창에 의사 상수 값이 선언됩니다 (정말 나쁜 생각입니다. 전역 변수를 부주의하게 선언해서는 안됩니다).

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에는 'const'선언이있는 새로운 ES6 표준이 있습니다.
위는 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키워드를 사용하십시오 .


그러나 정확한 크로스 브라우저 사전 정의 방법은 없으며 다른 답변에 표시된 변수 범위를 제어하여 달성 할 수 있습니다.

그러나 다른 변수와 구별하기 위해 이름 공간을 사용하는 것이 좋습니다. 이렇게하면 다른 변수의 충돌 가능성이 최소화됩니다.

다음과 같은 적절한 네임 스페이스

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

그래서 그것을 사용하는 동안 iw_constant.name또는iw_constant.age

또한 Object.freeze 메서드를 사용하여 iw_constant 내의 모든 새 키 추가 또는 키 변경을 차단할 수 있습니다. 그러나 레거시 브라우저에서는 지원되지 않습니다.

전의:

Object.freeze(iw_constant);

이전 브라우저의 경우 동결 방법에 polyfill사용할 수 있습니다 .


함수를 호출하는 것이 괜찮다면 상수를 정의하는 가장 좋은 크로스 브라우저 방법입니다. 자체 실행 함수 내에서 개체 범위를 지정하고 상수에 대한 get 함수를 반환합니다. 예 :

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모든 상수를 넣을 네임 스페이스 도 만들었습니다 . 다시, 오버 헤드와 함께. 쳇.

자, 난 그냥 할 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);
  };
}())

또한 보안이 실제로 문제인 것처럼 보이며 클라이언트 측에서 프로그래밍을 '숨길'방법이 없습니다. 저에게 좋은 생각은 여러분을 포함한 모든 사람이 그것을 읽고 이해하기가 정말 어렵도록 여러분의 코드를 압축하는 것입니다. 다음 사이트로 이동할 수 있습니다. http://javascriptcompressor.com/ . (이 사이트는 내 사이트가 아니므로 광고하지 않아도됩니다.)이 사이트는 무료로 Javascript 코드를 압축하고 난독화할 수있는 사이트입니다.

  1. 위 스크립트의 모든 코드를 복사하여 javascriptcompressor.com 페이지의 상단 텍스트 영역에 붙여 넣습니다.
  2. Base62 인코딩 확인란을 선택하고 변수 축소 확인란을 선택합니다.
  3. 압축 버튼을 누릅니다.
  4. 모든 파일을 .js 파일에 붙여넣고 저장하고 페이지 헤드의 페이지에 추가합니다.

이것은 표준화 된 크로스 브라우저 const 키워드의 필요성을 분명히 보여줍니다.

하지만 지금은 :

var myconst = value;

또는

Object['myconst'] = value;

둘 다 충분 해 보이고 다른 것은 바주카포로 파리를 쏘는 것과 같습니다.


내 Greasemonkey 스크립트 const대신 사용 var하지만 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와 Chromium에서는 상수, Safari와 Opera에서는 상수 (WTF?), IE에서는 변수를 제공합니다.

물론 eval ()은 사악하지만 IE가 없으면 IE는 오류를 발생시켜 스크립트가 실행되지 않도록합니다.

Safari와 Opera는 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);

이것은 무엇을 위해 좋은가요? 크로스 브라우저가 아니기 때문에 많지 않습니다. 기껏해야 적어도 일부 브라우저에서는 북마크릿이나 타사 스크립트가 값을 수정하지 못하도록하여 안심할 수 있습니다.

Firefox 2, 3, 3.6, 4, Iron 8, Chrome 10, 12, Opera 11, Safari 5, IE 6, 9에서 테스트되었습니다.


언급 할 가치가있는 경우 다음을 사용하여 각도로 상수를 정의 할 수 있습니다.$provide.constant()

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

대신 할 수있는 Burke의 답변 의 향상된 버전 CONFIG.MY_CONST입니다 CONFIG.get('MY_CONST').

IE9 + 또는 실제 웹 브라우저가 필요합니다.

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 (재) 모든 주요 브라우저 에서 지원되는 const키워드도입했습니다 .

를 통해 선언 된 변수는 const다시 선언하거나 다시 할당 할 수 없습니다.

그 외에도에서, const유사 동작합니다 let.

기본 데이터 유형 (Boolean, Null, Undefined, Number, String, Symbol)에 대해 예상대로 작동합니다.

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 키워드를 사용하면 변경 불가능한 문자열로 작동 할 값 / 문자열을 전달할 수 있습니다.


JavaScript에 상수를 도입하는 것은 기껏해야 해킹입니다.

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위에서 언급 한 것 외에 구현합니다 .

참고 URL : https://stackoverflow.com/questions/130396/are-there-constants-in-javascript

반응형