我目前正在使用 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 中隐藏变量?还是我在担心不该担心的事情?
最佳答案
要隐藏变量,可以使用闭包(函数作用域)
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
关于javascript - 如何在暴露公共(public)静态方法时在 Javascript 中使用 'hide' 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28253248/