[removed] constant properties

后端 未结 4 2023
独厮守ぢ
独厮守ぢ 2021-02-13 20:59

In javascript, can I declare properties of an object to be constant?

Here is an example object:

   var XU = {
      Cc: Components.classes
   };
<         


        
4条回答
  •  悲&欢浪女
    2021-02-13 21:44

    UPDATE: This works!

    const FIXED_VALUE = 37;
    FIXED_VALUE = 43;
    alert(FIXED_VALUE);//alerts "37"
    

    Technically I think the answer is no (Until const makes it into the wild). You can provide wrappers and such, but when it all boils down to it, you can redefine/reset the variable value at any time.

    The closest I think you'll get is defining a "constant" on a "class".

    // Create the class
    function TheClass(){
    }
    
    // Create the class constant
    TheClass.THE_CONSTANT = 42;
    
    // Create a function for TheClass to alert the constant
    TheClass.prototype.alertConstant = function(){
      // You can’t access it using this.THE_CONSTANT;
      alert(TheClass.THE_CONSTANT);
    }
    
    // Alert the class constant from outside
    alert(TheClass.THE_CONSTANT);
    
    // Alert the class constant from inside
    var theObject = new TheClass();
    theObject.alertConstant();
    

    However, the "class" TheClass itself can be redefined later on

提交回复
热议问题