1

I am trying to wrap my brains around the fact that something equals the value of the returned anonymous function value. I thought with scoping it wouldn't have had access to the functions variables.

So how does calling something give you the value of 3?

 function somefun (x){
     return function(){
         return x;
     }
 }

 var something = somefun (3);
 something();
 //3
Jamie Hutber
  • 26,790
  • 46
  • 179
  • 291

1 Answers1

2

In JavaScript, functions are just objects, like anything else. Functions can be assigned to variables.

So somefun returns a function, which is assigned to something. Thus, something is a function.

So, when something() is ran, it returns a value, because it's a function.

That function is called a "closure". It keeps a reference to the x value, which is why it's returned to you.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • so it runs the function, cool. argh pants. Makes sense now, as you gave the function to a variable. ekk i knew this. I just had a brain fart! – Jamie Hutber Feb 22 '13 at 16:05