1

I'm a java programmer and I'm trying to create something as close to a public static class in JS.

This is how I would code it in java:

class Static{
    private static final int privInt;
    public static int pubInt;

    static{
        privInt = 5;
    }

    public int pubMeth(){
        return privMeth();
    }

    private static int privMeth(){
         return false;
    }
}

I'm struggling to choose from two alternatives:

var Static1 = new function(){

   var privInt;
   this.pupInt = 5;

   privInt = 5;

   this.pupMeth = function(){
       return privMeth();
   };

   function privMeth(){
       return false;
   };

};


var Static2 =(function(){

   var privInt;

   privInt = 5;

   function privMeth(){
       return false;
   }

   return{

       pubInt: 5,
       pubMeth: privMeth

   };

})();

Maybe they're just syntactical flavours of the same thing, however netbeans are treating them differently? Which one should I go with, or is there yet another, better way?

kind user
  • 40,029
  • 7
  • 67
  • 77
Jake
  • 843
  • 1
  • 7
  • 18
  • in terms of scoping, there is no difference – Alex Mar 03 '17 at 11:57
  • go with first one – Mausam Sinha Mar 03 '17 at 11:57
  • If you have a static value, use `const` instead of `var`. Also choice would depend on the usage. Will this class have multiple instances? If yes, go with first. If you wish to have a singleton pattern go with second – Rajesh Mar 03 '17 at 11:58
  • 1
    Obligatory compatibility note for what @Rajesh suggested: `const` is only supported on IE11+. – Joe Clay Mar 03 '17 at 12:01
  • @Rajesh, I'm not sure how I could instantiate another Static1? Can it be extended or cloned? And if so, this can't be done with static2? – Jake Mar 03 '17 at 12:05
  • In JS you can define a function and use `new functionName()` to create an instance. So you can do it with `Static1` but since `Static2` is an object, you cannot. That structure is more suited for creating mixins – Rajesh Mar 03 '17 at 12:07
  • @Rajesh, I'm confused... So I could do: var static3 = new Static1(); ? – Jake Mar 03 '17 at 12:34
  • @Jake This might help you: http://stackoverflow.com/questions/1595611/how-to-properly-create-a-custom-object-in-javascript – Rajesh Mar 03 '17 at 12:40

1 Answers1

0

Even though I do not want to allow multiple instances of my class, I've decided to go with the "new function()" construction. This is mainly because it syntactically allows me to group private variables with their public interface. It also allows me to declare and execute my code in an order of my choosing, like calling a public method from a private one, whereas in the closure I'm forced to do my static logic before my public methods are declared, making this impossible.

Netbeans seem to like it much better as well. Closures seemed to make my private variables show up as public in the navigator view.

Jake
  • 843
  • 1
  • 7
  • 18