I came across this answer while understanding closures by @Jacob Swartwood https://stackoverflow.com/a/6472397/3179569
and I could not understand how littleGirl
called story as if it was a function. Shouldn't it have been littleGirl();
so that the princess
function was called? Also isn't the princess function returning a key value pair, which means it's returning an object? So how can littleGirl
access a key as if it was a function? (because story
is a key right?)
I tried searching for the term returning a key value pair in javascript but didn't come up with a decent explanation. I'm hoping someone here can help me. I come with a background in Java and C++ so this is a bit confusing.
function princess() {
var adventures = [];
function princeCharming() { /* ... */ }
var unicorn = { /* ... */ },
dragons = [ /* ... */ ],
squirrel = "Hello!";
return {
story: function() {
return adventures[adventures.length - 1];
}
};
}
var littleGirl = princess();
littleGirl.story();