Enlarging a local variable using JavaScript

I am trying to increment the counter, but I would like to move the variable from the global namespace and declare it locally. I am not sure how to do this. Thank you for your help.

This is the code I'm currently using.

var mediaClickCounter = 0;
function refreshMediaAds() {
    if (mediaClickCounter < 2) {
        mediaClickCounter++;
    } else {
        mediaClickCounter = 0;
        refreshAds();
    }
}
+3
source share
6 answers
// the function creates a local scope. 
var refreshMediaAds = (function() { 
    var mediaClickCounter = 0;
    // once executed it returns your actual function.
    return function _refreshMediaAds() {
        if (mediaClickCounter < 2) {
            mediaClickCounter++;
        } else {
            mediaClickCounter = 0;
            refreshAds();
        }
    }
// you execute the function.
})();

Closing <3.

+10
source

how to use something like this:

var ClickCounter = {
 mediaClickCounter: 0,

 refreshMediaAds:function() {
    if (this.mediaClickCounter < 2) {
        this.mediaClickCounter++;
    } else {
        this.mediaClickCounter = 0;
        refreshAds();
    }
 }
};

and then you can just use ClickCounter.refreshMediaAds()that to increase the member variable.

+2
source

, - . , , .

- , MooTools . : http://mootools.net/docs/core/Class/Class

+1

, ( , )

function refreshMediaAds(mediaClickCounter) {
    if (mediaClickCounter < 2) {
        mediaClickCounter++;
    } else {
        mediaClickCounter = 0;
        refreshAds();
    }
    return mediaClickCounter;
}
//then do: 
refreshMediaAds(clicks)
0
function refreshMediaAds() {
var mediaClickCounter = 0; // now variable have local scope.
    if (mediaClickCounter < 2) {
        mediaClickCounter++;
    } else {
        mediaClickCounter = 0;
        refreshAds();
    }
}
0

, , - . , IMO .

var refreshMediaAds = function() {
    var mediaClickCounter = 0;
    return function()
    {
        if (mediaClickCounter < 2) {
            mediaClickCounter++;
        } else {
            mediaClickCounter = 0;
            refreshAds();
        }
    }

}();

, , .

0

All Articles