如何在暴露公共静态方法的同时"隐藏"Javascript中的变量?

Sco*_*ley 6 javascript static-methods

我目前正在使用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))
Run Code Online (Sandbox Code Playgroud)

这是有效的,但它暴露mars.x给其他代码,这些代码实际上不需要了解它.如果我使用prototype这些方法将不再是静态的,代码将被new调用,我真的不想要.

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

Aze*_*rah 9

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

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
Run Code Online (Sandbox Code Playgroud)