有没有办法访问javascript闭包内声明的变量?
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
var CLOSURE_VAR = (function() {
var privateVar = {
arr: []
};
return {
setVar: function(name,name2) {
privateVar['arr'][name] = name2;
},
getVar: function(name) {
return privateVar['arr'][name];
},
getPrivateVar: function(name) {
return privateVar[name];
}
};
}());
function initializeArr(name) {
CLOSURE_VAR.setVar(name,"y");
CLOSURE_VAR.setVar("def","z");
}
function checkVar(name) {
alert(CLOSURE_VAR.getVar(name));
console.log(CLOSURE_VAR.getPrivateVar('arr')+"--------------------");
alert(CLOSURE_VAR.getVar("def"));
}
</script>
</head>
<body onload="initializeArr('abc')">
<a href="#" onclick="checkVar('abc')">hello</a>
</body>
</html>
页面加载时我将值插入数组中。当我点击链接时,我想获得数组(带数据),如[abc:“y”,def:“z”],但MODULE.getPrivateVar('arr')返回空白;
答案 0 :(得分:0)
您将arr
声明为数组而不是对象。
运行此代码段:
var CLOSURE_VAR = (function() {
var privateVar = {
arr: {}
};
return {
setVar: function(name, name2) {
privateVar['arr'][name] = name2;
},
getVar: function(name) {
return privateVar['arr'][name];
},
getPrivateVar: function(name) {
return privateVar[name];
}
};
}());
function initializeArr(name) {
CLOSURE_VAR.setVar(name, "y");
CLOSURE_VAR.setVar("def", "z");
}
function checkVar(name) {
console.log(CLOSURE_VAR.getVar(name));
console.log(JSON.stringify(CLOSURE_VAR.getPrivateVar('arr')) + "--------------------");
console.log(CLOSURE_VAR.getVar("def"));
}
initializeArr('abc');
&#13;
<a href="#" onclick="checkVar('abc')">hello</a>
&#13;
请参阅?现在正在打印对象。
arr
从Array[]
更改为Object{}
。stringify
将该对象的版本作为String。