JavaScript 跨多个文件的模块模式
JavaScript Module Pattern across multiple files
我必须重组一些古老的代码,很多不同的文件中都有很多。该方法是使用揭示模块模式,如 JavaScript Module Pattern: In-Depth(跨文件私有状态部分)所述。
第一个函数表达式效果很好,我可以在 Firebug 中看到第二个块中的函数组件也被正确分配。但随后变量突然未定义。
我整理了一个简化的example,第二次赋值后控制台显示变量未定义
var test = (function ($, ns, undefined)
{
function test1()
{
console.log("executing test1");
ns.testx.test2();
}
return { test1: test1 };
}(jQuery, test || {}));
console.log(test);
var test = (function ($, ns, undefined)
{
ns.testx = (function ()
{
function test2()
{
console.log("executing test2");
}
return { test2: test2 }
})();
}(jQuery, test || {}));
console.log(test);
// DOM ready
$(function ()
{
test.test1();
});
几个变体,例如在顶部只定义一次变量也不起作用。如果交换两个函数表达式,则执行测试 1 但 ns.testx 未定义。
我担心我错过了非常明显的东西,我真的很想知道为什么这不起作用。我还需要让它工作,所以非常感谢任何帮助(将文件合并为一个不是一个选项)。
尝试
var test = (function ($, ns, undefined)
{
function test1()
{
console.log("executing test1");
ns.testx.test2();
}
ns.test1 = test1;
return ns;
}(jQuery, test || {}));
console.log(test);
var test = (function ($, ns, undefined)
{
ns.testx = (function ()
{
function test2()
{
console.log("executing test2");
}
return { test2: test2 }
})();
return ns;
/*
This will be
{
test1: test1,
testx: {
test2: test2
}
}
*/
}(jQuery, test || {}));
我必须重组一些古老的代码,很多不同的文件中都有很多。该方法是使用揭示模块模式,如 JavaScript Module Pattern: In-Depth(跨文件私有状态部分)所述。
第一个函数表达式效果很好,我可以在 Firebug 中看到第二个块中的函数组件也被正确分配。但随后变量突然未定义。
我整理了一个简化的example,第二次赋值后控制台显示变量未定义
var test = (function ($, ns, undefined)
{
function test1()
{
console.log("executing test1");
ns.testx.test2();
}
return { test1: test1 };
}(jQuery, test || {}));
console.log(test);
var test = (function ($, ns, undefined)
{
ns.testx = (function ()
{
function test2()
{
console.log("executing test2");
}
return { test2: test2 }
})();
}(jQuery, test || {}));
console.log(test);
// DOM ready
$(function ()
{
test.test1();
});
几个变体,例如在顶部只定义一次变量也不起作用。如果交换两个函数表达式,则执行测试 1 但 ns.testx 未定义。
我担心我错过了非常明显的东西,我真的很想知道为什么这不起作用。我还需要让它工作,所以非常感谢任何帮助(将文件合并为一个不是一个选项)。
尝试
var test = (function ($, ns, undefined)
{
function test1()
{
console.log("executing test1");
ns.testx.test2();
}
ns.test1 = test1;
return ns;
}(jQuery, test || {}));
console.log(test);
var test = (function ($, ns, undefined)
{
ns.testx = (function ()
{
function test2()
{
console.log("executing test2");
}
return { test2: test2 }
})();
return ns;
/*
This will be
{
test1: test1,
testx: {
test2: test2
}
}
*/
}(jQuery, test || {}));