As a followup to this question still trying to grok Javascript function anomalies, can someone explain why the following code works?
My text (Javascript Patterns) states:
If you create a new function and assign it to the same variable that already holds another function, you’re overwriting the old function with the new one.
Which would make me assume that in the following code, the variables count and name would be clobbered when the second definition of the function test is created.
Where are the variables count and name living on?
$(document).ready(function() {
var test = function() {
var name = 'The Test Function';
var count = 1;
console.log(name + ' has been setup');
test = function() {
console.log('Number of times ' + name + ' has been called: ' + count);
count++;
};
}
test();
test();
test();
test();
test();
});
Output:
