FEE Test Submission

1. A closure is when you want to access a variable inside a function which would normally be closed off due to scope. The privateCounter and changeBy function are both private to the makeCounter function, but they can be accessed through the two public functions that makeCounter returns. In this case the privateCounter variable will not be garbage collected and still be accessible in memory.


var makeCounter = function() {
  var privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  }
  return {
    increment: function() {
      changeBy(1);
    },
    value: function() {
      return privateCounter;
    }
  }  
};
var Counter = makeCounter();
$("#keypressExample").keyup(function(){ 
	Counter.increment();  
	var counterValue = Counter.value();
	alert("You have pressed " + counterValue + " keys")

});

Here I was able to access the otherwise closed variable privateCounter through the use of a closure. And I will be able to access new instances of this counter for different methods, each having their own privateCounter value.

2. Object function constructor is the preferred way to declare an object in javascript. This way you can create different attributes and methods for the object with the object prototype.

		
			function car(model) {
			this.model = model;
			}
			var Car = car("Mercedes");
			car.prototype.vroom = function(){
			alert(this.model +" goes Vroom!");
			}
			Car.vroom();

		
	

3. Find the code at the bottom of html