Look at the flow carefully:
var routes = function() {
var person = {
fname: 'Roger',
lname: 'Federer',
city: 'Paris'
}
var fun = {
getData:function() {
return person
}
}
return fun;
}
var x = routes();
console.log(x.getData());
First you defined the anonymous function.
When the anonymous function is called it:
- Defines the object
person
(locally in its internal own scope)
Defines the object fun
(also in its own internal scope)
When it defines fun
it also defines the method getData()
which returns person
- declared in the outer scope (inside the outermost anonymous function which we just described).
The outer most anonymous function finishes by returning fun
.
Then you call the anonymous function. (Via routes()
.)
Calling routes()
returns fun
, which means you can do routes().getData()
and it resolves through to that getData:function() {
declaration.
As we've said, that returns the person
object from the scope of the outermost anonymous function. It's accessible to the definition of getData()
- so it gets resolved OK.
When you called var x = routes()
you captured the return value of routes()
- which is fun
because that's what routes()
returns. You just made a more complicated route to get to x.getData()
. Nothing wrong with that!
So in short:
x
is the fun
object returned by routes()
fun
has a method called getData()
, which returns person
person
happens to be defined within the scope of an anonymous function - which you executed when calling routes()
(specifically you did var x = routes();
- which triggered the creation of person
).
I hope that makes sense.
It's not "super obvious", but the code is pretty easy to follow if you work through it line-by-line in order of execution, keeping a mental note (or on paper) of scopes and variable values.
Update: Others are providing worthwhile reading links on the subject of JavaScript closures. Read those. It'll teach you what I've stated above. They're more worthy (IMHO) of an up-vote. My answer is simply an explanation of the execution of the code you provided - not a walk-through on closures. :)