变量范围和共享信息没有全局变量

时间:2013-05-14 21:48:35

标签: javascript jquery

如果我有:

function firstFunction(){
    var counter = 0;
    secondFunction();
    secondFunction();
    secondFunction();
    secondFunction();
}
function secondFunction(){
    counter++;
}

由于变量的局部范围,我收到错误,但是如果不使用全局变量,我还能做些什么呢?

4 个答案:

答案 0 :(得分:7)

一种方法是使用闭包:

(function() {
    var counter = 0;

    function firstFunction() {
        secondFunction();
        secondFunction();
        secondFunction();
        secondFunction();
    }

    function secondFunction() {
        counter++;
    }
})();

或者,您可以将counter的值传递给secondFunction,如下所示:

function firstFunction() {
    var counter = 0;
    counter = secondFunction(counter);
    counter = secondFunction(counter);
    counter = secondFunction(counter);
    counter = secondFunction(counter);
}

function secondFunction(counter) {
    return ++counter;
}

答案 1 :(得分:1)

使用Object按引用传递计数器

   function firstFunction() {

        var myObj = new Object();
        myObj.counter = 0;

        secondFunction(myObj);
        secondFunction(myObj);
        secondFunction(myObj);
        secondFunction(myObj);

    }

    function secondFunction(obj) {
        obj.counter++;
    }

答案 2 :(得分:1)

由于javascript中的原始类型(如整数和字符串)是按值传递的,但是对象是通过引用传递的,因此需要使用一个对象:

// passing primitive type
var counter = 0;
for (var i = 0; i < 4; ++i) { 
    secondFunction(counter);
}
alert(counter); // 0
function secondFunction(counter) {
    counter++;
}

// passing object
var obj = { counter: 0 }
for (var i = 0; i < 4; ++i) { 
    secondFunction(obj);
}
alert(obj.counter); // 4
function secondFunction(obj) {
    obj.counter++;
}

http://jsfiddle.net/MpVqQ/2/

通过这种方式,您可以在不使用全局变量的情况下实现所需。

答案 3 :(得分:0)

作为Elliot Bonneville答案的补充,你也可以这样做:

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

关于某些闭包变量的暴露......继续努力,这是一个重要的理解模式,我保证!