我目前正在尝试为我的 javascript 应用程序创建一个测试套件。我的问题是,我似乎无法从我的 utils 对象访问 init(),如下所示:
我的应用遵循单例模式:
var appModal = function () {
var utils = Object.create(moduleUtils);
function init(caller, options ) {
}
}();
我的测试套件在moduleUtils中,这是一个转换为原型(prototype)的对象字面量
moduleUtils.debug = {
addSlideTest : function(){
/* this function cannot fire init() from appModal */
}}
最佳答案
这是不可能的。
您需要在公开可见的对象中公开闭包函数。
例如,您可以在单元测试中创建一个testMethods
对象来收集私有(private)方法。然后,如果对象存在,您的主文件将向该对象添加私有(private)方法,如下所示:
//In appModal
if (typeof testMethods === "object")
testMethods.init = init;
//In test suite
testMethods = { };
...
testMethods.init();
关于javascript - 如何从其中的另一个对象访问单例中的 'private functions',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2800018/