我试图了解如何在javascript中按文件分解功能。我试图将名称空间视为单例类。我不明白为什么在下面的代码中,MODULE_A.privateMethod1()
会抛出错误:Uncaught TypeError: undefined is not a function
。当我打开已记录的对象时,我无法在那里看到私有方法。
的index.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);
})();
moduleA.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");
}
}
})();
答案 0 :(得分:3)
解决方案是两者中的一个:
当您使用var
声明某些内容时,无法使用this
:
this.privateMethod1 = function() {
console.log("A.privateMethod1");
};
或
publicMethod1: function() {
console.log("B.publicMethod1");
this.publicMethod2();
privateMethod1();
privateMethod2();
},
编辑:如果您希望将该方法设为私有,则应遵循方法2,您可以转到this site获取更多说明。