Although code like this is probably not best practice, I ran into something strange while working the other day. Recreating it as a simple example, I expected the following code to alert 'dog' and then 'cat', but instead it alerted 'dog' twice. By my understanding of JavaScript closure, that seems like very odd behavior to me. Anyone have a good explanation for this?
var printMan = {
printer: function(animal){
this.innerPrinter = this.innerPrinter || function(){
alert(animal)
}
this.innerPrinter(animal)
}
}
printMan.printer('dog' )
printMan.printer('cat')
Here's the Fiddle
Edit ----- Thanks everyone for the great explanations. This is one of the reasons why I love this language - there's a great community here. I thought I knew a great deal about the language, but I was wrong about how this function would work. For anyone reading this, it's probably best to not do something like this example.
this.innerPrinteris pointing to the first ever result and it is not a function anymore.cacheis technically not the correct word to describe it, but it does (at least loosely) describes the process...thisas a side-effect. That is, it only exists (on printMan) afterprintMan.printer()and is never used externally and captures the first (and then stale) variable.