0
var count = 0; 

function goFast(){
    ++count;
    console.log("Go straight and then ");
    var direction = "right"; if (count%2===0){direction="left";}
    turn(direction);
    console.log("Thank you passenger #" + count);
}

var turn = function(direction) {
    console.log("turn to your " + direction)
}

goFast();
goFast();

The goFast function is in charge of counting how many travelers pass through, and asks another function where they should turn (which logs out left or right alternatively).

How can I bring my count variable inside the goFast function and thus better encapsulate it, but without re-initializing it every time the function is invoked of course?

Here is a jsfiddle: http://jsfiddle.net/legolandbridge/sU8T8/

collardeau
  • 800
  • 7
  • 13

3 Answers3

4

One approach would be to wrap it in a closure and return a function that has access to the count variable. For e.g.

var goFast = (function() {
    var count = 0;
    return function() {
        ++count;
        console.log("Go straight and then ");
        var direction = "right"; if (count%2===0){direction="left";}
        turn(direction);
        console.log("Thank you passenger #" + count);
    };
})();
source.rar
  • 8,002
  • 10
  • 50
  • 82
3

Wrap its definition in another function to create a temporary scope.

var goFast = (function() { 
   var count = 0;
   return function() {
       ++count;
       console.log("Go straight and then ");
       var direction = "right"; if (count%2===0){direction="left";}
       turn(direction);
       console.log("Thank you passenger #" + count);
   };
})();
DrC
  • 7,528
  • 1
  • 22
  • 37
  • Thank you, this is exactly what I was looking for. I had seen this technique before but could not reproduce it with this simple example. – collardeau Jun 08 '14 at 11:09
0

You could do something like this, but it's not the prettiest and since turn is not inside goFast() anyways.. yeah don't see the benefit.:

function goFast(){
    if ( !window.count )
            window.count = 0;
    ++count;
    console.log("Go straight and then ");
    var direction = "right"; if (count%2===0){direction="left";}
    turn(direction);
    console.log("Thank you passenger #" + count);
}

var turn = function(direction) {
    console.log("turn to your " + direction)
}

goFast();
goFast();

http://jsfiddle.net/daCrosby/sU8T8/1/

DACrosby
  • 11,116
  • 3
  • 39
  • 51