简体   繁体   English

javascript中的公共静态对象

[英]public static object in javascript

I'm a java programmer and I'm trying to create something as close to a public static class in JS. 我是一个java程序员,我正在尝试创建一些与JS中的公共静态类接近的东西。

This is how I would code it in java: 这就是我在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? 也许它们只是同一种语法的语法风格,但是netbeans对它们的处理方式不同? Which one should I go with, or is there yet another, better way? 我应该选择哪一个,还是有另一个更好的方法?

Even though I do not want to allow multiple instances of my class, I've decided to go with the "new function()" construction. 即使我不想允许我的类的多个实例,我决定采用“new function()”构造。 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. Netbeans似乎也喜欢它。 Closures seemed to make my private variables show up as public in the navigator view. 闭包似乎使我的私有变量在导航器视图中显示为公共变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM