Static variables in JavaScript

后端 未结 30 2613
别那么骄傲
别那么骄傲 2020-11-22 01:55

How can I create static variables in Javascript?

30条回答
  •  孤城傲影
    2020-11-22 02:40

    To condense all class concepts here, test this:

    var Test = function() {
      // "super private" variable, accessible only here in constructor. There are no real private variables
      //if as 'private' we intend variables accessible only by the class that defines the member and NOT by child classes
      var test_var = "super private";
    
      //the only way to access the "super private" test_var is from here
      this.privileged = function(){
        console.log(test_var);
      }();
    
      Test.test_var = 'protected';//protected variable: accessible only form inherited methods (prototype) AND child/inherited classes
    
      this.init();
    };//end constructor
    
    Test.test_var = "static";//static variable: accessible everywhere (I mean, even out of prototype, see domready below)
    
    Test.prototype = {
    
     init:function(){
       console.log('in',Test.test_var);
     }
    
    };//end prototype/class
    
    
    //for example:
    $(document).ready(function() {
    
     console.log('out',Test.test_var);
    
     var Jake = function(){}
    
     Jake.prototype = new Test();
    
     Jake.prototype.test = function(){
       console.log('jake', Test.test_var);
     }
    
     var jake = new Jake();
    
     jake.test();//output: "protected"
    
    });//end domready
    

    Well, another way to take a look to best practices in these things, is to just see how coffeescript translates these concepts.

    #this is coffeescript
    class Test
     #static
     @prop = "static"
    
     #instance
     constructor:(prop) ->
       @prop = prop
       console.log(@prop)
    
     t = new Test('inst_prop');
    
     console.log(Test.prop);
    
    
    //this is how the above is translated in plain js by the CS compiler
      Test = (function() {
        Test.prop = "static";
    
        function Test(prop) {
         this.prop = prop;
         console.log(this.prop);
        }
    
        return Test;
    
      })();
    
      t = new Test('inst_prop');
    
      console.log(Test.prop);
    

提交回复
热议问题