【问题标题】:How do I 'hide' variables in Javascript whilst exposing public static methods?如何在暴露公共静态方法的同时在 Javascript 中“隐藏”变量?
【发布时间】:2015-03-30 22:52:53
【问题描述】:

我目前正在使用 Javascript 重写一些科学的 C++ 代码,如果可能的话,我希望保持相同的基本组织。在 C++ 代码中,有许多类包含来自许多不同数组的一堆 const 数据和一系列处理该数据的 public static 方法。我正在努力解决如何在 Javascript 中复制这样的内容。

目前我正在使用以下内容:

function mars(){}

mars.x = [{A:1, B:2, C:3},{A:1, B:2, C:3}]; //...
mars.y = [{A:1, B:4, C:2},{A:1, B:2, C:3}]; //...
// ...about 600 lines in total

mars.doSomething = function(foo){
    var result = 0;
    // Do lots of processing of above arrays
    return result;
}

mars.doSomethingElse = function(bar){
    var result = 0;
    // Do lots of processing of above arrays
    return result;
}

console.log(mars.doSomething(3))

这可行,但它会将mars.x 等暴露给真正不需要知道它的其余代码。如果我使用prototype,方法将不再是静态的,代码中会充斥着new 调用,这是我并不真正想要的。

然后我要问的是:如何在 JavaScript 中隐藏变量,同时将静态方法暴露给其余代码?还是我在担心不该担心的事情?

【问题讨论】:

  • 剩下的代码是指类的方法吗?
  • 你在担心不该担心的事情!
  • @Sprotenwels 不,我的意思是其他 50 个左右的类价值函数(总共数百个函数)。感觉好像我在全球乱扔了很多其他大多数班级都不需要知道的东西。
  • 那么@Azeirah 的答案就是你应该追求的目标
  • 这是 Node.js 还是客户端?

标签: javascript static-methods


【解决方案1】:

只需将其设为局部变量并使用 getter 函数来获取它们。另外,尽量保持命名方案。对于构造函数来说,就是名字应该以大写字母开头。

function Mars(){
   var x = [{A:1, B:2, C:3},{A:1, B:2, C:3}];
   this.getArr = function(){
       return x;
   }
}
var mars = new Mars();
mars.x; // undefined
mars.getArr(); // [Object, Object]

【讨论】:

    【解决方案2】:

    要隐藏变量,可以使用闭包(函数作用域)

    function mars () {
      var staticFunctions = Object.create(null); // the same as {}
      var x = [{A:1, B:2, C:3},{A:1, B:2, C:3}];
      var y = [{A:1, B:4, C:2},{A:1, B:2, C:3}];
    
      staticFunctions.doSomething = function (foo) {
        return x;
      };
    
      staticFunctions.doSomethingElse = function (bar) {
        return y;
      };
    
      return staticFunctions;
    }
    
    // you do need to instantiate mars however
    var m = mars();
    // if you don't want that you can do
    var mars = (function () {
        // same as above
    } ()); // this invokes the function for you
    

    【讨论】:

      【解决方案3】:

      你担心这个是对的。如果你不解决这个问题,你的代码将变得难以管理。

      您使用函数来控制 JavaScript 中的范围。 JS 没有类。 ES6(未广泛使用)有“类”,但只是名义上的。

      你可以试试这样的:

      var myApp = {};
      
      (function(namespace){
      
        var X = [{A:1, B:2, C:3},{A:1, B:2, C:3}]; // Capitalized because 'constant'.
        var Y = [{A:1, B:4, C:2},{A:1, B:2, C:3}]; // Capitalized because 'constant'.
      
        function Mars () {} // Capitalized because this is a constructor function.
      
        Mars.prototype.doSomething = function(foo) {
          //do something with X
          return X[foo]; // For example.
        }
      
        namespace.mars = new Mars(); // Lowercase on 'namespace.mars' because it is an instance.
      
      }(myApp))
      
      
      // Use...
      myApp.mars.doSomething(foo); // Does something.
      Mars; // undefined
      X; // undefined
      Y; //undefined
      

      【讨论】:

        【解决方案4】:

        我认为下面的示例可以让您深入了解私有、公共和静态变量和方法。

        function Mars(){
          // private variables
          var x = [{A:1, B:2, C:3},{A:1, B:2, C:3}];
          var y = [{A:1, B:4, C:2},{A:1, B:2, C:3}]; 
        
          // public variables
          this.z = 2;
        
          // privileged methods, can access private variables
          this.getX = function(){
              return x;
          };
        
          this.getY = function(){
              return y;
          };  
        }
        
        // public prototype method, can not access private variables
        // access private variables through getters
        Mars.prototype.getZ = function(){
          return this.z;
        }
        
        // static variable
        Mars.staticVar = 1;
        
        // static method
        Mars.staticMethod = function(){
           console.log('It is the static method');
        }
        
        
        
        var marsObj = new Mars();
        console.log(marsObj.getX()); //Array [ Object, Object ]
        console.log(marsObj.getZ()); //2
        
        Mars.staticMethod(); // "It is the static method"
        marsObj.staticMethod(); // Exception: mars.staticMethod is not a function
        

        要了解 JavaScript 中的 OOPS,我推荐本教程: http://phrogz.net/JS/classes/OOPinJS.html

        【讨论】:

          【解决方案5】:

          我看到您想提供一些结构并组织您的 javascript 代码。这最好在 Javascript 中处理,即众所周知的 Module Pattern

          简而言之,它的工作原理是这样的:

          var MODULE = (function () {
              var my = {},
                  privateVariable = 1;
          
          
              function privateMethod() {
                  // ...
              }
          
              my.moduleProperty = 1;
              my.moduleMethod = function () {
                  // ...
              };
          
              return my;
          }());
          

          此 sn-p 和进一步阅读记录在 Ben Cherry's articleEric Miraglia's 文章中。模块模式有一些巧妙的变体,例如Christian Heilmann 揭示的模块模式

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2010-10-13
            • 2011-10-08
            • 1970-01-01
            • 1970-01-01
            • 2019-05-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多