function buildCoveTicketMarker(transport){ var passengerNumber = 0; return function(name){ passengerNumber++; alert("Ticket via the " +transport+ "Welcome, "+ name+ "#"+passengerNumber+"."); } } var getSubmarineTicket = buildCoveTicketMarker("Submarine"); //passengerNumber number is 1 var getTrianTicket = buildCoveTicketMarker("Train"); //passengerNumber number is 2
The code shows it is still possible the change the variable of the closure in the background.
--------------------------Ex------------------------------------
function warningMaker( obstacle ){ var count = 0; return function ( number, location ) { count++; alert("Beware! There have been " + obstacle + " sightings in the Cove today! " + number + " " + obstacle + "(s) spotted at the " + location + "! "+ "This is Alert #"+ count+ " today for "+ obstacle+ " danger." ); }; } //Save location also function warningMaker( obstacle ){ var count = 0; var locaitons = []; return function ( number, location ) { locaitons.push(location); count++; alert("Beware! There have been " + obstacle + " sightings in the Cove today! " + number + " " + obstacle + "(s) spotted at the " + location + "! " + "This is Alert #" + count + " today for " + obstacle + " danger. "+ "Current danger zones are: " + locaitons.map(function(place){return place+" ";}) ); }; } //Create a zone object to store location and num function warningMaker( obstacle ){ var count = 0; var zones = []; var zone = {}; zone.location = ""; zone.num = 1; return function ( number, location ) { count++; var flag = false; for(var j = 0; j < zones.length; j++){ if(zones[j].location === location){ zones[j].num++; flag = true; } } if(!flag){ zone.location = location; zone.num = 1; zones.push(zone); } var list = ""; for(var i = 0; i<zones.length; i++){ list = list + " " + zones[i].location+" ("+zones[i].num+")"; } alert("Beware! There have been " + obstacle + " sightings in the Cove today! " + number + " " + obstacle + "(s) spotted at the " + location + "! " + "This is Alert #" + count + " today for " + obstacle + " danger. " + "Current danger zones are: " + list ); }; }