我一直在寻找最佳解决方案,这是在任意数量的JavaScript文件中使用命名空间和子命名空间的最佳解决方案。我在StackOverflow上阅读了很多文章和答案,我的选择是JavaScript Module Pattern。
但是我有一个问题是如何避免将命名空间定义添加到只有子命名空间定义的每个文件中:
// How to avoid namespace definition
var appModule = (function(ns) {
return ns;
}(appModule || {}));
// I want to have only this
appModule.sub2 = (function (ns) {
ns.publicFunction5 = function() {
console.log('publicFunction5 from sub2AppModule.js');
};
return ns;
}(appModule.sub2 || {}));
在 Pure JavaScript 中的多个文件中使用命名空间和子命名空间可能是更好的方法。
我的整个例子是为了更好地理解我的情况。
的index.html
<!DOCTYPE html>
<html>
<head>
<title>Test namespace and sub-namespace in multiple files</title>
<!-- order is intentional to check any order attaching files -->
<script src="sub2AppModule.js"></script>
<script src="sub1AppModule2.js"></script>
<script src="sub1AppModule.js"></script>
<script src="appModule2.js"></script>
<script src="appModule.js"></script>
<script>
function testNamespace() {
console.log(appModule.publicVariable1);
appModule.publicFunction1();
appModule.publicFunction2();
appModule.sub1.publicFunction3();
appModule.sub1.publicFunction4();
appModule.sub2.publicFunction5();
}
</script>
</head>
<body>
<h1>Test namespace</h1>
<button onclick="testNamespace()">Run test</button>
</body>
</html>
appModule.js
var appModule = (function(ns) {
var privateVariable1 = 'privateVariable1';
function privateFunction1() {
console.log('privateFunction1 from appModule.js');
}
ns.publicVariable1 = 'publicVariable1 from appModule.js';
ns.publicFunction1 = function() {
console.log('publicFunction1 from appModule.js');
console.log('publicFunction1 display ' + privateVariable1);
console.log('publicFunction1 call ' + privateFunction1());
// Call function from nested namespace
appModule.sub2.publicFunction5();
};
return ns;
}(appModule || {}));
appModule2.js
var appModule = (function(ns) {
ns.publicFunction2 = function() {
console.log('publicFunction2 from appModule2.js');
};
return ns;
}(appModule || {}));
sub1AppModule.js
var appModule = (function(ns) {
return ns;
}(appModule || {}));
appModule.sub1 = (function(ns) {
ns.publicFunction3 = function() {
console.log('publicFunction3 from sub1AppModule.js');
// Call function from parent namespace
appModule.publicFunction2();
};
return ns;
}(appModule.sub1 || {}));
sub1AppModule2.js
var appModule = (function(ns) {
return ns;
}(appModule || {}));
appModule.sub1 = (function (ns) {
ns.publicFunction4 = function() {
console.log('publicFunction4 from sub1AppModule2.js');
};
return ns;
}(appModule.sub1 || {}));
sub2AppModule.js
var appModule = (function(ns) {
return ns;
}(appModule || {}));
appModule.sub2 = (function (ns) {
ns.publicFunction5 = function() {
console.log('publicFunction5 from sub2AppModule.js');
};
return ns;
}(appModule.sub2 || {}));