Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I 'hide' variables in Javascript whilst exposing public static methods?

I am currently rewriting some scientific C++ code using Javascript and I would like to keep the same basic organisation if at all possible. In the C++ code, there are a number of classes that contain a bunch of const data in the from of many different arrays and a series of public static methods that work on that data. I'm struggling with how to replicate something like this in Javascript.

At the moment I'm using something like the following:

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))

This works, but it exposes mars.x etc. to the rest of the code which really doesn't need to know about it. If I use prototype the methods will no longer be static and the code will be littered with new calls, something I don't really want.

What I'm asking then, is: How do I hide variables in JavaScript whilst exposing static methods to the rest of the code? Or am I worrying about something I shouldn't be?

like image 792
Scott Marley Avatar asked Jan 31 '15 15:01

Scott Marley


1 Answers

To hide a variable, you can use a closure (function scope)

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
like image 192
Azeirah Avatar answered Oct 30 '22 22:10

Azeirah