The key idea here is that when a function references a variable from an outer scope - for example in this case the talk
function is referencing the bark
variable which comes from the outer scope - that's called a closure.
The variable is held by the function itself and, by design of the language, can't be directly accessed by the "outside world". It's only accessible by the outside world if you choose to expose it, for example as part of the return value from the function.
If you wanted a version where bark
could be changed, you would have to do something like this:
var dog = function(){
var theDog = {
bark: "bark",
talk: function() {
console.log(this.bark);
}
};
return theDog;
}
var fido = dog()
fido.bark = "BARK BARK" //Why does this not change the bark inside the function?
fido.talk()
(A more idiomatic version would likely use a Dog
constructor function but I'm trying to keep it as close to the original code as possible)
The MDN article on closures is quite good for more information on closures.