JavaScript中有常量吗?

JavaScript中有常量吗?,javascript,constants,Javascript,Constants,有没有办法在JavaScript中使用常量 如果没有,指定用作常量的变量的常见做法是什么?没有,一般不这样。Firefox实现了const,但我知道IE没有 指向一种常见的常量命名方法,这种方法在其他语言中已经使用了多年,我认为没有理由不使用它。当然,这并不意味着有人无论如何都不会写变量的值。:) 从那时起,JavaScript的概念是: 这将在未来起作用。有些可能还需要启用 您可以将var与诸如ALL_CAPS之类的约定一起使用,以表明如果需要支持旧浏览器或使用旧代码,则不应修改某些值: v

有没有办法在JavaScript中使用常量


如果没有,指定用作常量的变量的常见做法是什么?

没有,一般不这样。Firefox实现了const,但我知道IE没有


指向一种常见的常量命名方法,这种方法在其他语言中已经使用了多年,我认为没有理由不使用它。当然,这并不意味着有人无论如何都不会写变量的值。:)

从那时起,JavaScript的概念是:

这将在未来起作用。有些可能还需要启用

您可以将
var
与诸如ALL_CAPS之类的约定一起使用,以表明如果需要支持旧浏览器或使用旧代码,则不应修改某些值:

var MY_CONSTANT = "some-value";

我在Greasemonkey脚本中使用
const
而不是
var
,但这是因为它们只在Firefox上运行…
名称约定也确实是一种方法(我两者都做!)。

有一段时间,我在传递给
with()
语句的对象文本中指定了“常量”(实际上仍然不是常量)。我觉得它很聪明。下面是一个例子:

with ({
    MY_CONST : 'some really important value'
}) {
    alert(MY_CONST);
}
在过去,我还创建了一个
CONST
名称空间,在那里我可以放置所有常量。再一次,用头顶。嘘


现在,我只做
var MY_CONST='whatever'到。

您是否试图保护变量不被修改?如果是,则可以使用模块模式:

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()方法


如果您不需要严格保护变量值,那么只需按照建议执行,并使用所有大写的约定。

中有
const
关键字,但到目前为止,它只获得少量浏览器支持:。语法为:

const CONSTANT_NAME = 0;

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>

常数=真
如果(测试类型=未定义){
常数IE_const=假;
}
警报(即常数);

在JavaScript中,我的首选是使用函数返回常量值

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


alert(MY_CONSTANT());

ECMAScript 5确实引入了:

它(和IE一样)好≥ 9)


另请参见:

在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时
然后马上就清楚了。

您可以很容易地为脚本配备一种可以设置但不能更改的常量机制。尝试更改常量将产生错误

/* 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  
包含有关
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标准的定义良好和常用功能的支持,包括let、
const
Map
Set
WeakMap
,以及改进互操作性的
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu>


好吧,这很难看,但它在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);
这有什么用呢?没什么用,因为它不是跨浏览器的。顶多也可以放心,至少有些浏览器不会让bookmarklet或第三方脚本修改值


使用Firefox 2、3、3.6、4、Iron 8、Chrome 10、12、Opera 11、Safari 5、IE 6、9进行测试。

忘记IE,使用
const
关键字。

在JavaScript中引入常量充其量只是一种攻击

在JavaScript中创建持久性和全局可访问值的一个好方法是声明一个对象文本,其中包含一些“只读”属性,如:

            my={get constant1(){return "constant 1"},
                get constant2(){return "constant 2"},
                get constant3(){return "constant 3"},
                get constantN(){return "constant N"}
                }
const name1 = value;
您将把所有常量分组到一个“我的”附件对象中,您可以在其中查找存储的值或任何其他您决定放在其中的内容。现在让我们测试它是否有效:

           my.constant1; >> "constant 1" 
           my.constant1 = "new constant 1";
           my.constant1; >> "constant 1" 
如我们所见,“my.constant1”属性保留了其原始值。您已经为自己制作了一些漂亮的“绿色”临时常量

但当然,这只会保护您不被意外地修改、更改、取消或清空属性常量值,就像在t中一样
           my.constant1; >> "constant 1" 
           my.constant1 = "new constant 1";
           my.constant1; >> "constant 1" 
/*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);
  };
}())
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;
var obj = {};
Object.defineProperty(obj, 'CONSTANT', {
  configurable: false
  enumerable: true,
  writable: false,
  value: "your constant value"
});
Object.defineProperty(this, 'constant', {
  enumerable: true, 
  writable: false, 
  value: 7, 
  configurable: false
});

> constant
=> 7
> constant = 5
=> 7
var myconst = value;
Object['myconst'] = value;
var iw_constant={
     name:'sudhanshu',
     age:'23'
     //all varibale come like this
}
Object.freeze(iw_constant);
var iw_constant= (function(){
       var allConstant={
             name:'sudhanshu',
             age:'23'
             //all varibale come like this

       };

       return function(key){
          allConstant[key];
       }
    };
var constant = function(val) {
   return function() {
        return val;
    }
}
a = constant(10);

a(); // 10

b = constant(20);

b(); // 20
"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
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 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;
}());
angularApp.constant('YOUR_CONSTANT', 'value');
const name1 = value;
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;
}
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