作为补充埃利奥特巴纳维亚的答案,你也可以这样做:
var firstFunction = (function()
{
var counter = 0,
secondFunction = function
{
counter++;
};
return function()
{
counter = 0;//initialize counter to 0
secondFunction();
return counter;
};
};
console.log(firstFunction());//logs 1, because counter was set to 1 and returned
这一切变得有点多,但谷歌“的JavaScript模块模式”和调查一下。你很快就会发现什么使这个代码打勾:
var counterModule = (function()
{
var counter = 0,
secondFunction = function
{
counter++;
},
firstFunction = function()
{
counter = 0;//initialize counter to 0
secondFunction();
},
getCounter = function()
{
return counter;
}
setCounter = function(val)
{
counter = +(val);
};
return {firstFunction: firstFunction,
getCounter: getCounter,
setCounter: setCounter};
};
console.log(counterModule.firstFunction());//undefined
console.log(counterModule.getCounter());//1
console.log(counterModule.secondFunction());//ERROR
这是所有关于某些闭包变量的曝光......坚持下去的工作,这是需要理解的重要模式,我答应!
传递参数? –