The first parameter is stored locally in the function that is your constructor, so anywhere inside Student() it will be in scope.
More interestingly, the anonymous inner function that you assign this.getFirst closes this value. Because of this, the internal function maintains a reference to the first variable even after the constructor completes.
This also works for regular functions, and not just for constructors:
function makeCounter() { var count = 1; return function() { return count++; }; } var counter = makeCounter(); console.log(counter());
When used correctly, this approach can be used to achieve "private" variables in JavaScript, in the sense that the values ββfixed in the closure are not accessible from the outside.
Because of this, it turns out that it does not matter if the closure covers all the variables in its scope or only those that it uses, since you cannot "get inside" these closed variables anyway. (Although in practice, only the values ββused are usually fixed, so the runtime can garbage collect the rest because they are not needed.)
source share