Reputation: 8009
How to alter the JavaScript code below so that it can avoid exposing the variables and functions to the global scope?
var nMax = 10;
var i = 0;
var step = function(){
//do stuff
i += 1;
if(i < nMax){
step();
}else{
alert('finished');
}
}
step();
Ideally it would be grateful if the reason behind it could be provided.
Any idea would be very much appreciated!
Upvotes: 1
Views: 837
Reputation: 3077
Put in an object so fn gets called via that:-
var stepHolder = {};
stepHolder.step = (function(nMax){
var i = 0;
return function step(){
//do stuff
i += 1;
if(i < nMax){
step();
}else{
alert('finished');
}
};}
)(10);
stepHolder.step();
Upvotes: 0
Reputation: 359776
An alternative to using a closure: functions are objects, so you can attach values to them just like any other object:
function step()
{
step.i++;
if (step.i < step.nMax) step();
else alert('finished');
}
step();
Or, use an object to namespace the function and variables:
var stepper =
{
i: 0,
nMax: 10,
step: function ()
{
this.i++;
if (this.i < this.nMax) this.step();
else alert('finished');
}
};
stepper.step();
And here's a cleaner version of @PaulPRO's answer which uses a function declaration rather than a function expression:
(function ()
{
var i = 0,
nMax = 10;
function step()
{
i++;
if (i < nMax) step();
else alert('finished');
}
step();
})();
Upvotes: 1
Reputation: 44376
The standard way would be
var step = function(){
var nMax = 10;
var i = 0;
return function() {
//do stuff
i += 1;
if(i < nMax){
step();
}else{
alert('finished');
}
};
}();
step();
Upvotes: 2
Reputation: 141829
Just wrap it in an anonymous function, and call that function immediately:
(function(){
var nMax = 10;
var i = 0;
var step = function(){
//do stuff
i += 1;
if(i < nMax){
step();
}else{
alert('finished');
}
}
step();
})();
Another Example: http://jsfiddle.net/n5Srd/
Upvotes: 4