TonyTakeshi
TonyTakeshi

Reputation: 5929

Are these javascript closures?

Refering to How do JavaScript closures work?.

Closure is:

Just want to confirm are the following consider closure?

1) Binding javascript function within a function.

var Books = {
    init:function(){
        $('#box').bind('click',function(){
           console.log('click'); 
        });
    }
};

Books.init();​

2) Declare a function within a function

function sayHello(name) {
  var text = 'Hello ' + name;
  var sayAlert = function() { alert(text); }
}   

var hello = sayHello();

I still can't differentiate which is closure for some times, is that all function within function consider closure or only the one that keep the returned inner function as variable/reference. Example:

function sayHello(name) {
  var text = 'Hello ' + name;
  var sayAlert = function() { alert(text); }
  **return sayAlert;**
}

Upvotes: 0

Views: 93

Answers (2)

NimChimpsky
NimChimpsky

Reputation: 47280

1 isn't as no variables are actually referenced, 2 and 3 are.

In 2 and 3 the variable called text is closed off - referenced outside its lexical scope. In 1 nothing is.

crockford on closures :

What this means is that an inner function always has access to the vars and parameters of its outer function, even after the outer function has returned.

Upvotes: 1

Ariel
Ariel

Reputation: 26753

All of those are closures.

I'm not sure what your confusion is.

Upvotes: 0

Related Questions