Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this closure work?

Say I have a simple function that alerts a message:

function callMessage(msg){
        alert(msg);
    }

Now when I call it like so, it does not work. Throws error "hey is not defined"

function sayHi(){
        var hey = "hi there"
        setTimeout("callMessage(hey)", 1000);
    }
    sayHi();

But when I call it inside an anonymous function it does work:

function sayHi(){
        var hey = "hi there"
        setTimeout(function(){callMessage(hey);}, 1000);
    }
    sayHi();

Why is the "hey" variable only visible when I put it inside an anonymous function?

like image 796
levi Avatar asked Mar 01 '12 15:03

levi


People also ask

What is closure and how it works?

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.

How does closure work in JavaScript?

A Closure is a combination of a function enclosed with references to its surrounding state (the lexical environment). In JavaScript, closures are created every time a function is created at run time. In other words, a closure is just a fancy name for a function that remembers the external things used inside it.

What is a closure and why are they so useful to us?

A closure is simply a more convenient way to give a function access to local state. Rather than having to create a class which knows about the local variable you want the function to use, you can simply define the function on the spot, and it can implicitly access every variable that is currently visible.

What is the advantage of closure?

Advantages of closures They allow you to attach variables to an execution context. Variables in closures can help you maintain a state that you can use later. They provide data encapsulation. They help remove redundant code.


2 Answers

In the first example, the code is evaluated after the timer expired and the current scope was left. hey is undefined at that moment.

The second example - the proper way to use setTimeout - uses an anonymous function created when invoking setTimeout(). This anonymous function also receives a copy of the current scope.

like image 86
Linus Kleen Avatar answered Sep 18 '22 06:09

Linus Kleen


"callMessage(hey)" is a string, not a closure. It's evaluated when the timeout runs, and at this point the variable hey isn't in scope.

like image 41
Ben Clayton Avatar answered Sep 20 '22 06:09

Ben Clayton