Are there constants in JavaScript?

后端 未结 30 3187
抹茶落季
抹茶落季 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条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 09:32

    You can easily equip your script with a mechanism for constants that can be set but not altered. An attempt to alter them will generate an error.

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

提交回复
热议问题