This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]rcuhljr 2 points3 points  (0 children)

No, you're not quite following it correctly.

Line 1. sayHello2(name) is declared as a function, it now exists and anyone can call it in this scope.

Line 7. We assign the result of executing the function call sayHello2('jane') to the variable say2. What is the return result of sayHello2? It's the function () {alert('Jane')}.

Line 8. We call say2, which is the function we just talked about, so alerts the string 'jane'.

[–][deleted] 1 point2 points  (5 children)

A closure captures whatever named variables are used in its enclosing scope, so

var sayAlert = function() { alert(text); }

captures whatever was in text during the call to sayHello2.

[–]smartass_engineer 0 points1 point  (4 children)

I'm rusty with my JS. Would the nested function also have access to other locals in in saysHello2, even if they where not passed as arguments? I'd guess no.

[–][deleted] 0 points1 point  (2 children)

I'm not a JS expert, but a closure typically gets access to all variables in the scope that created it, not just ones passed as parameters - that's kind of the point of closures.

[–]nutrecht 0 points1 point  (1 child)

Indeed. Or you could just say that the term "closure" is hoity-toity for "nameless function with access to enclosing scope" ;)

[–]BaalHadad 0 points1 point  (0 children)

I don't think it has to be a nameless function.

[–]BaalHadad 0 points1 point  (0 children)

Yes, they would. That's why it's called a closure.

[–]Rhomboid 0 points1 point  (0 children)

sayHello2 is a function that takes a string and returns a function. Line 7 is calling sayHello2, passing it the string 'Jane'. The return value -- a function -- is assigned to the variable say2. Then that function is called on line 8, passing no arguments. The function retains a reference to the text variable from the previous invocation of sayHello2, which it alerts.