0

I have a question,please see the code snippet,i can see it's invoked in some js libraries.

Can anyone tell me what's the excuting order of this snippet? On my perspective, first ,the compiler declares a variable A. When come to excuting time,it defines a function and assigns it to variable A ,But in function body,the variable A can't reference anywhere since the 'var A' is still not been asigned to a funciton.

I hope that I've expressed my quesion clearly.

Tell me where I am wrong.

    var A= function(){reutrn A;}
    console.log(A()()().....)    /*no mater how many '()'s,it still returns the "function (){return A }" */
johnny_trs
  • 233
  • 1
  • 2
  • 6
  • 1
    The reference to `A` inside the function will be to the `var` declared *outside* the function. Other than that it's not really clear what you're asking. – Pointy Apr 20 '16 at 15:10
  • 1
    possible duplicate of [How do JavaScript closures work?](http://stackoverflow.com/q/111102/1048572) – Bergi Apr 20 '16 at 15:14
  • 3
    The function `A` returns whatever is assigned to the variable `A` (same thing incidentally) *at the time it's called*. – deceze Apr 20 '16 at 15:14
  • @Bergi ,I don't think so – johnny_trs Apr 20 '16 at 15:21
  • 2
    @johnny_trs: It seems to explain your misconception "*But in function body,the variable A can't reference anywhere*", doesn't it? – Bergi Apr 20 '16 at 15:24

1 Answers1

2

But the function is assigned to A! That's exactly what that first line means. Here's how it actually works:

var A; // Definitions are "hoisted" to the top of the scope.
A = function() {
  return A; // Return whatever value is bound to "A", this may change
            // before the function is run
};
A(); // "A" is a function, return that function
A()(); // Since the value of "A" hasn't changed, we again return that function
// Ad infinitum...

There are two key elements to understanding this: hoisting and the fact that values captured inside of a function may change before the function is called.

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91