Are there constants in JavaScript?

后端 未结 30 2611
抹茶落季
抹茶落季 2020-11-22 08:53

Is there a way to use constants in JavaScript?

If not, what\'s the common practice for specifying variables that are used as constants?

30条回答
  •  旧时难觅i
    2020-11-22 09:41

    "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
    

    See Object.freeze. You can use const if you want to make the constants reference read-only as well.

提交回复
热议问题