我试图了解如何通过 javascript 中的文件分解功能。我试图将命名空间视为单例类。我不明白为什么在下面的代码中MODULE_A.privateMethod1()
会抛出错误:Uncaught TypeError: undefined is not a function
. 当我打开记录的对象时,我也看不到那里的私有方法。
索引.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test Project</title>
<script src="index.js"></script>
<script src="moduleA.js"></script>
</head>
<body>
<div>
hi
</div>
</body>
</html>
index.js:
(function() {
var initializeWindow = function() {
console.log("initializeWindow");
MODULE_A.publicMethod1();
};
window.addEventListener('load', initializeWindow);
})();
模块A.js:
// "Singleton Class"
var MODULE_A = (function() {
// ---------------------------------------------------------------------------
// "Private" Class Constants
// ---------------------------------------------------------------------------
var A_CONSTANT_NUMBER = 1;
// ---------------------------------------------------------------------------
// "Private" Class Variables (Properties)
// ---------------------------------------------------------------------------
var myPrivateVar_ = 2;
// ---------------------------------------------------------------------------
// "Private" Methods
// ---------------------------------------------------------------------------
var privateMethod1 = function() {
console.log("A.privateMethod1");
};
var privateMethod2 = function() {
console.log("A.privateMethod2");
};
return {
// ---------------------------------------------------------------------------
// "Public" Class Variables (Properties)
// ---------------------------------------------------------------------------
aPublicVar1: 3,
// ---------------------------------------------------------------------------
// "Public" Methods
// ---------------------------------------------------------------------------
publicMethod1: function() {
console.log("A.publicMethod1");
this.publicMethod2();
// ERROR HERE!!!
this.privateMethod1();
this.privateMethod2();
},
publicMethod2: function() {
console.log("A.publicMethod2");
}
}
})();