JavaScript에 상수가 있나요?
JavaScript에서 상수를 사용하는 방법이 있나요?
그렇지 않은 경우 상수로 사용되는 변수를 지정하는 일반적인 방법은 무엇입니까?
ES2015 이후 JavaScript의 개념은 다음과 같습니다.
const MY_CONSTANT = "some-value";
IE 8, 9, 10을 제외한 거의 모든 브라우저에서 작동합니다.또, 엄밀한 모드를 유효하게 할 필요가 있는 경우도 있습니다.
하시면 됩니다.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
이 방법을 사용하면 값을 변경할 수 없습니다.단, CONFIG :()에서는 get() 메서드를 사용해야 합니다.
변수 값을 엄격하게 보호할 필요가 없는 경우 권장하는 대로 수행하고 ALL CAPS 규칙을 사용합니다.
const
키워드는 ECMAScript 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
'오브젝트'를 참조해 주세요.멈춰요. 만약 당신이 그것을 만들고 싶다면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 (window,'CONSTANT',{ value : 5, writable: false });
최신 브라우저(및 IE © 9)에서 지원됩니다.
다음 항목도 참조하십시오.ES5의 Object.defineProperty?
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★Firefox는 「」를 .const
IE の 는렇는
@John은 여러 해 동안 다른 언어로 사용되어 온 Const의 일반적인 명명 관행을 지적하고 있는데, 그것을 사용하지 못할 이유는 없다고 생각한다.물론 그것이 누군가가 변수의 값을 덮어쓰지 않는다는 것을 의미하지는 않습니다.:)
JavaScript에서는 함수를 사용하여 상수값을 반환하는 것을 선호합니다.
function MY_CONSTANT() {
return "some-value";
}
alert(MY_CONSTANT());
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와 무엇을 하고 있을까요?지금까지는 지원하지 않기로 했습니다.모든 브라우저에서 사용할 수 있는 것은 아니기 때문에 아직 컨센서스 기능은 아닙니다.
...
결국 웹을 위한 최선의 장기적인 해결책은 웹을 배제하고 표준화 프로세스가 실행될 때까지 기다리는 것입니다.
다른 브라우저가 제대로 구현하지 않아서 구현이 안 된다고?!더 낫게 만드는 게 너무 두려운가?표준 정의 여부에 관계없이 상수는 상수입니다. 한 번 설정하면 변경되지 않습니다.
덮어쓸 수 ( 등XSS라고 합니다. 때문에 이 경우에도 차이가 없습니다.var
★★★★★★★★★★★★★★★★★」function(){return}
const
유일한 진짜 상수입니다.
업데이트: IE11 지원 const
:
IE11에는 새롭게 등장한ECMAScript 6 규격의 잘 정의되어 일반적으로 사용되는 기능에 대한 지원이 포함되어 있습니다.예를 들어, 다음과 같습니다.
Map
,Set
, , , , 입니다.WeakMap
, , ,와 .__proto__
이치노
기능을 사용해도 괜찮다면:
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"
});
자세한 내용은 Mozilla 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은 '상수' 선언이 있는 새로운 ES6 표준을 채택하고 있다.
상기의 기능은, IE8, IE9, IE10등의 이전의 브라우저로 동작합니다.
를 무시하고 를 합니다.const
키워드를 지정합니다.
설정할 수 있지만 변경할 수 없는 상수에 대한 메커니즘을 스크립트에 쉽게 장착할 수 있습니다.변경하려고 하면 오류가 발생합니다.
/* 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
그러나 브라우저 간에는 정확한 사전 정의된 방법이 없습니다.다른 답변에 나타난 바와 같이 변수의 범위를 제어함으로써 이를 달성할 수 있습니다.
그러나 다른 변수와 구별하기 위해 이름 공간을 사용할 것을 제안합니다.이렇게 하면 다른 변수에서 충돌할 가능성이 최소화됩니다.
다음과 같은 적절한 네임스페이스 사용
var iw_constant={
name:'sudhanshu',
age:'23'
//all varibale come like this
}
그래서 사용하는 동안iw_constant.name
★★★★★★★★★★★★★★★★★」iw_constant.age
오브젝트를 사용하여 새로운 키를 추가하거나 iw_constant 내의 키를 변경하는 것을 차단할 수도 있습니다.프리즈 방식그러나 레거시 브라우저에서는 지원되지 않습니다.
예:
Object.freeze(iw_constant);
오래된 브라우저에서는 freeze 메서드에 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);
}
과거에도, 나는, I creasure를 작성했다.CONST
모든 상수를 넣을 수 있는 네임스페이스입니다.하다, 하다, 하다 she.
ㅇㅇㅇ, ㅇㅇㅇㅇ...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;
나도 이것에 대해 문제가 있었다.그리고 답을 찾고 모든 사람들의 반응을 살펴본 후, 저는 이것에 대한 실행 가능한 해결책을 생각해냈다고 생각합니다.
제가 발견한 대부분의 답변은 함수를 사용하여 상수를 유지하는 것 같습니다.MANY 포럼의 많은 사용자가 투고하듯이 클라이언트 측 사용자가 쉽게 함수를 덮어쓸 수 있습니다.저는 상수 객체는 외부에서 접근할 수 없고 내부의 함수에서만 접근할 수 있다는 키이스 이브츠의 대답에 흥미를 느꼈습니다.
그래서 저는 이 해결책을 생각해냈습니다.
클라이언트 측에서 변수, 오브젝트 등을 변경하지 않도록 모든 것을 익명 함수에 넣습니다.또한 다른 함수가 내부에서 '실제' 함수를 호출하도록 하여 '실제' 함수를 숨깁니다.또, 클라이언트측 유저에 의해서 기능이 변경되고 있지 않은지, 기능을 사용해 확인하려고 생각하고 있습니다.기능이 변경된 경우 내부에서 '보호'되고 변경할 수 없는 변수를 사용하여 다시 변경하십시오.
/*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 코드를 무료로 압축 및 난독화할 수 있는 사이트입니다.
- 위 스크립트의 모든 코드를 복사하여 javascriptcompressor.com 페이지의 상단 텍스트 영역에 붙여넣습니다.
- [ Base 62 encode ]체크박스를 켜고 [Shrink Variables]체크박스를 켜겠습니다
- Compress(압축) 버튼을 누릅니다.
- 모든 파일을 .js 파일로 붙여넣고 저장하여 페이지 선두에 있는 페이지에 추가합니다.
이는 표준화된 크로스 브라우저 const 키워드의 필요성을 분명히 보여줍니다.
하지만 지금으로서는:
var myconst = value;
또는
Object['myconst'] = value;
둘 다 충분해 보이고 다른 것은 바주카로 파리를 쏘는 것과 같다.
용 i i i i를 쓴다.const
var
그리스몽키
이름 표기법도 정말 좋은 방법이 될 수 있다.
JavaScript에서는 가능한 한 상수를 피하고 대신 문자열을 사용합니다.상수를 외부에 노출하려는 경우 상수와 관련된 문제가 나타납니다.
예를 들어 다음과 같은 Date 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가 오류를 발생시켜 스크립트가 실행되지 않습니다.
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에서 테스트 완료.
언급할 가치가 있는 경우 다음을 사용하여 각도 상수를 정의할 수 있습니다.
angularApp.constant('YOUR_CONSTANT', 'value');
버크의 대답의 개량된 버전으로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
는 와 유사하게 동작합니다.
원시 데이터 유형(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
불하 just just just just just just just just just : 그냥 쓰다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"
사실로 남아있을 것이다.
상수가 이미 존재합니다.상수는 다음과 같이 정의합니다.
const name1 = value;
이것은 재할당을 통해 변경할 수 없습니다.
'const'라는 키워드는 앞서 제안되었고 이제 공식적으로 ES6에 포함되었습니다.const 키워드를 사용하면 불변의 문자열로 동작하는 값/스트링을 전달할 수 있습니다.
자바스크립트에 상수를 도입하는 것은 기껏해야 해킹이다.
JavaScript에서 영구적이고 글로벌하게 액세스할 수 있는 값을 만드는 좋은 방법은 다음과 같은 "읽기 전용" 속성을 사용하여 개체 리터럴을 선언하는 것입니다.
my={get constant1(){return "constant 1"},
get constant2(){return "constant 2"},
get constant3(){return "constant 3"},
get constantN(){return "constant N"}
}
모든 상수를 하나의 "my" 액세서리 개체로 그룹화하여 저장된 값이나 해당 문제에 대해 지정한 다른 값을 검색할 수 있습니다.이제 동작하는지 테스트해 보겠습니다.
my.constant1; >> "constant 1"
my.constant1 = "new constant 1";
my.constant1; >> "constant 1"
보시다시피 "my.constant1" 속성은 원래 값을 유지합니다.'녹색'의 좋은 임시 상수를 만들었군
그러나 물론 이는 주어진 예시와 같이 직접 액세스를 통해 속성 상수 값을 실수로 수정, 변경, 무효화 또는 비우지 않도록 보호할 뿐입니다.
그렇지 않으면 상수는 멍청이들을 위한 것이라고 생각한다.그리고 나는 여전히 당신의 위대한 자유를 기만적인 안보의 작은 구석에 맞바꾸는 것은 최악의 거래라고 생각한다.
Rhino.js
를 실장하다const
상기의 내용에 가세해 주세요.
언급URL : https://stackoverflow.com/questions/130396/are-there-constants-in-javascript
'programing' 카테고리의 다른 글
pytest에서 예외가 발생한다고 올바르게 주장하는 방법은 무엇입니까? (0) | 2023.01.21 |
---|---|
MariaDB에서 윈도우 기능이 느립니까? (0) | 2023.01.21 |
junit & java : 비공개 메서드 테스트 (0) | 2023.01.21 |
C에서 Linux와 공유 메모리를 사용하는 방법 (0) | 2023.01.21 |
PHP interafce mysql()은 동작하지 않지만 mysqli()는 동작합니다.왜일까요? (0) | 2023.01.21 |