我正在尝试使用模块化模式编写我的javascript代码,但是我在调用内部函数时遇到问题,并且还存在一些安全问题。我可以轻松打开控制台并输入我的命名空间名称。变量并更改变量值。
JS
下面的 JS 代码工作正常,但正如我所说,我可以从控制台更改 gridValue。我该如何避免这种情况。我将在我的所有函数中使用这个变量。
var myTicTacToe = {
turn:'X',
score: {
'X': 0,
'O': 0
},
gridValue: 0,
fnLoad:function () {
var select = document.getElementById("grid");
for (i = 3; i <= 100; i += 1) {
var option = document.createElement('option');
select.options[select.options.length] = new Option(i + ' X ' + i, i);
}
}
}
window.onload = function(){
myTicTacToe.fnLoad();
}
下面的一个在调用 fnLoad 时给我带来了问题。
var myTicTacToe = function(){
var turn = 'X',
score = {
'X': 0,
'O': 0
},
gridValue = 0,
fnLoad = function () {
var select = document.getElementById("grid");
for (i = 3; i <= 100; i += 1) {
var option = document.createElement('option');
select.options[select.options.length] = new Option(i + ' X ' + i, i);
}
}
}
window.onload = function(){
myTicTacToe.fnLoad();
}
- 如何保护我的 gridValue 或第一个模式中的任何变量?
- 为什么我无法像第一个那样调用 fnLoad ?我该怎么调用它?
- 这两种模式有什么区别?
- 在第一个代码中,当我使用 var 声明任何变量时,它给了我错误。为什么会这样?
最佳答案
您指的是Revealing Module Pattern 。一切都是私有(private)的除非您明确返回
var myTicTacToe = (function(){
var turn = 'X',
score = {
'X': 0,
'O': 0
},
gridValue = 0,
fnLoad = function () {
var select = document.getElementById("grid");
for (i = 3; i <= 100; i += 1) {
var option = document.createElement('option');
select.options[select.options.length] = new Option(i + ' X ' + i, i);
}
};
<b>return {
load: fnLoad //fnLoad is now publicly named "load".
};</b>
})();
window.onload = function(){
myTicTacToe.load();
}
/* Or even
window.onload = myTicTacToe.load; //Because it's a single function.
*/
至于您的具体问题:
- 你不能。默认情况下,使用普通模块模式,所有对象成员都是公共(public)的。
- 因为您尚未
退回
它,所以请参阅上面的示例。 - 一种允许私有(private)成员,另一种则不允许。暴露的图案允许私密。
- 我不明白我们在谈论哪个变量。但如果它是对象成员,则不应使用
var
声明它。
关于使用模块化模式时不会调用 Javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25486006/