开发者

Avoid using global variables and functions in Javascript

开发者 https://www.devze.com 2023-03-28 03:06 出处:网络
How to alter the JavaScript code below so that i开发者_运维技巧t can avoid exposing the variables and functions to the global scope?

How to alter the JavaScript code below so that i开发者_运维技巧t 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!


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/


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();


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();
})();


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消