简体   繁体   English

避免在 Javascript 中使用全局变量和函数

[英]Avoid using global variables and functions in Javascript

How to alter the JavaScript code below so that it can avoid exposing the variables and functions to the global scope?如何更改下面的 JavaScript 代码,以避免将变量和函数暴露给全局 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 中,然后立即调用 function:

(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/另一个例子: 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:使用闭包的替代方法:函数是对象,因此您可以像任何其他 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:或者,使用 object 命名 function 和变量:

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:这是@PaulPRO 答案的更简洁版本,它使用 function 声明而不是 function 表达式:

(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:-放入 object 以便通过以下方式调用 fn:-

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM