假设我有以下 javascript:
function Foo() {
function privateStuff() {
//do private stuff
}
this.publicStuff = function() {
privateStuff();
//do other stuff
}
}
通过执行以下操作很容易测试 publicStuff()
:
var myFoo = new Foo();
myFoo.publicStuff();
//all the assertions
但是,我希望能够将 privateStuff()
方法作为它自己的单元进行测试。我不确定我怎么能自己调用它。我知道使用 Java(我更熟悉它)可以使用反射来测试私有(private)方法,但我想知道是否有任何方法可以自行测试这些函数。如果没有通用的方法,我已经开始研究 Jasmine运行我的单元测试。该框架是否为此提供了任何功能?
最佳答案
按照您将代码放在那里的方式,您不能。您不允许任何对象对 privateStuff
进行范围内访问。在我看来,您需要阅读闭包的概念(这是 JavaScript 的基础)。
每当您在 JS 中使用 f() { ... }
构造(以及其他几个,如 try-catch
block )时,您总是隐式创建一个闭包.像您那样嵌套函数是完全合法的,但除非您为外部函数提供对内部函数的外部引用,否则只能从外部函数内部访问内部函数。
来自 Mozilla :
You can nest a function within a function. The nested (inner) function is private to its containing (outer) function. It also forms a closure.
A closure is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).
Since a nested function is a closure, this means that a nested function can "inherit" the arguments and variables of its containing function. In other words, the inner function contains the scope of the outer function.
- The inner function can be accessed only from statements in the outer function.
- The inner function forms a closure: the inner function can use the arguments and
尽管 Mozilla 文档延续了这一点,但在 Javascript 中说东西是 private
或 public
是有点不正确的,因为命名法在大多数编程语言中都有非常明确的含义(如 C++ 和 Java)与多态行为或继承相关。就 JS 而言,最好将其视为范围受限的,并尝试深入了解闭包。
关于javascript - 您如何测试仅在闭包范围内可见的 javascript 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12084590/