I have the following code:
function bird(type) {
return function (whattosay) { //return the whole function
console.log (type + ' ' + whattosay)
}
}
var birdRef = bird('blackbird');
birdRef('singing in the dead of night');
var secondRef = bird('whitebird');
birdRef('singing after that night');
I am trying to get familiar with two concepts, closure and scope chain. Well, at my first birdRef I get in return a new function object, then I invoke it after that line line. At the end I see "blackbird singing in the dead of night" in the console. I understand that in order to find the bird type var, the closure gives you a reference to the parent, and It's somewhat looks for that var in the scope chain and finally finds it, so we see the type of the bird.
Well then you have this:
var secondRef = bird('whitebird');
A new argument has been passed, so now the var "type" changed in the bird function from blackbird to whitebird.
Now I come back to my previous created function birdRef, the thing I don't understand is, what happens next:
birdRef('singing after that night');
I get "blackbird singing after that night", instead of whitebird. Well, If I am not mistaken, doesn't the birdRef function comes to it's parent function bird, and reads the type of the updated bird variable(what I mean is that he couldn't find that var in the local environment, so he looked in the outer environment and found the var "type")?
Sorry if I don't make much sense as I am new to this, and thank you for your time.