作爲補充埃利奧特巴納維亞的答案,你也可以這樣做:
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
這是所有關於某些閉包變量的曝光......堅持下去的工作,這是需要理解的重要模式,我答應!
傳遞參數? –