在只有 nodejs 的环境中在 ES6 Module/Class 中定义 'real' 私有方法,没有任何信息泄漏

Define 'real' private methods in ES6 Module/Class in a nodejs only environment without any information leak

我知道没有 REAL 私有方法 INSIDE ES6 classes。但是我玩了一会儿,发现了一些好东西 - 也许......

正如我提到的,不公开对象的属性是不可能的。但是我试图实现一些 OOP 编程,因为我将 classes 分成单独的文件,然后导出这些 classes,例如:

class MyClass {
  constructor() {
    /**
     * Initialize stuff...
     */
  }

  myMethod() {
    /**
     * Do public stuff...
     */
  }

}

// expose class to environment.
export default MyClass;

所以我可以导入 class:

import MyClass from './MyClass.js';

当然 myMethod 可以从导入该模块的任何其他文件访问。由于我需要只能由 class 访问的变量和函数,我试过这个:

// private variable outside of class scope but still accessible.
let possiblePrivateVariable = 'am I a private variable?';

class MyClass {
  constructor() {
    /**
    * Initialize stuff...
    */
  }

  myMethod() {
    // run private method.
    console.log(_possiblePrivateMethod());
    // show private variable.
    console.log(possiblePrivateVariable);
  }

}

// private function outside of class scope but still accessible.
function _possiblePrivateMethod() {
  return 'am I a private method?';
}

// expose class to environment.
export default MyClass;

现在不能访问私有变量和私有方法:

// Import class to newFile.js and use it.
import MyClass from './MyClass.js';

const exposedClass = new MyClass();
exposedClass.possiblePrivateVariable;   // -> undefined.
exposedClass._possiblePrivateMethod();  // -> undefined.
exposedClass. myMethod();               // -> logs: am I a private method?
                                        //          am I a private variable?

很明显,那些人感觉像蜜蜂 'private' 因为我没有用 export 这个词来暴露他们。我的问题是这种方法是否可以考虑创建私有变量和方法?如果我展示的方法在 运行 代码时有任何其他可能的泄漏?

此致, 巨人


旁注:我不需要浏览器支持,因为它是一个纯 NodeJS 环境。我正在使用 NodeJS v8.1.4 并在我的 npm start 脚本中使用 babel 所以我可以使用 import 而没有任何 TypeError

我还应该提一下,我知道这个问题可以被视为重复问题,但这不是因为这个问题不是关于 class 内部而是外部的私有属性、变量和方法.

My question is if this method can be considered creating private variables and methods?

是的,这是解决 ES6/7/8 不处理 类 隐私问题的实际解决方案。

And if the Method I've shown has any other possible leakage while running the code?

快速回答:无泄漏

详细答案:

在您的私有函数系统中,使函数私有的原因是在 javascript 中,函数的范围由定义它的位置来定义。在你的情况下文件。

如果不把函数导出到文件外,就没法访问了。就像你无法访问以下主流示例中的功能:

function toto() {
 const tmpToto = () => console.log('Hello');

 // I can access tmpToto from here
 tmpToto();

 return false;
}

// I cannot access tmpToto from here

Here 你对作用域有了很好的解释


更多信息根据评论

How would you solve the problem that multiple class instances will share the 'out of scope' variables?

您可以使用 IIFE(Immediately-invoked function expression) as described by @Son JoungHo in .

let Name = (function() {
  const _privateHello = function() {}

  class Name {
    constructor() {}

    publicMethod() {
      _privateHello();
    }
  }

  return Name;
})();