Questions tagged [closures]

A closure is a first-class function that refers to (closes over) variables from the scope in which it was defined. If the closure still exists after its defining scope ends, the variables it closes over will continue to exist as well.

A closure is a first-class function that refers to (closes over) variables from the scope in which it was defined. If the closure still exists after its defining scope ends, the variables it closes over will continue to exist as well.

JavaScript closure

A basic example of closure in JavaScript can be shown with a counter:

function increment () {
    var count = 0;
    return function () { // returning function
         count++; // increment the count
         return count;
    };
}

var foo = increment(); // foo is now a closure function, where count = 0
foo(); // calls the closure which yields 1

The reason why increment is considered to be a closure is because it's a local variable. In this case, count is persisting when assigned to the variable foo. This persistence occurs because the context of foo is taken from increment when it's declared.

The key point with a closure is that the environment of the function is 'closed' to a hosting object.

var bar = increment(); // bar is now another closure function, with count initialized to 0
bar(); // calls the closure which yields 1, not 2.

jQuery closures

A more practical example of a closure is the jQuery library. jQuery itself is one big closure. It's declared like this:

var jQuery = (function() { // Here is the closure
    // Define a local copy of jQuery
    var jQuery = function( selector, context ) {
        // The jQuery object is actually just the init constructor 'enhanced'.
        return new jQuery.fn.init( selector, context, rootjQuery );
    },
    ...
}) ( window );

Let's take a deeper look at this. jQuery's closure is actually an immediately invoked function expression or a closure that is immediately called. Let's take our original increment example and represent it in the form that jQuery uses:

var foo = (function () {
    var count = 0;
    return function () {
        count++; // Increment the count
        return count;
    };
}) ();

foo(); // Yields 1

At first glance, this looks quite a bit different from our original example, but take another look. The only difference is that this example is wrapped in parentheses. (function () {...}) ();. These parentheses are returning the result of what's inside of them.

The first parentheses are returning a function that has count = 0. This is the same as calling increment() in our first example and the second set of parentheses is calling the returned function.

Resources

For a history of closures as a programming language construct see the Wikipedia Closure page.

In Ruby, closures are called blocks.

8908 questions
127
votes
10 answers

nonlocal keyword in Python 2.x

I'm trying to implement a closure in Python 2.6 and I need to access a nonlocal variable but it seems like this keyword is not available in python 2.x. How should one access nonlocal variables in closures in these versions of python?
adinsa
  • 1,271
  • 2
  • 9
  • 3
125
votes
8 answers

How do I run Asynchronous callbacks in Playground

Many Cocoa and CocoaTouch methods have completion callbacks implemented as blocks in Objective-C and Closures in Swift. However, when trying these out in Playground, the completion is never called. For example: // Playground - noun: a place where…
ikuramedia
  • 6,038
  • 3
  • 28
  • 31
123
votes
2 answers

Cell-var-from-loop warning from Pylint

For the following code: for sort_key, order in query_data['sort']: results.sort(key=lambda k: get_from_dot_path(k, sort_key), reverse=(order == -1)) Pylint reported an error: Cell variable sort_key defined in loop…
xis
  • 24,330
  • 9
  • 43
  • 59
120
votes
12 answers

Calling closure assigned to object property directly

I would like to be able to call a closure that I assign to an object's property directly without reassigning the closure to a variable and then calling it. Is this possible? The code below doesn't work and causes Fatal error: Call to undefined…
Kendall Hopkins
  • 43,213
  • 17
  • 66
  • 89
119
votes
6 answers

How do I pass the value (not the reference) of a JS variable to a function?

Here is a simplified version of something I'm trying to run: for (var i = 0; i < results.length; i++) { marker = results[i]; google.maps.event.addListener(marker, 'click', function() { change_selection(i); }); } but I'm…
ryan
  • 2,311
  • 3
  • 22
  • 28
116
votes
4 answers

Local variables in nested functions

Okay, bear with me on this, I know it's going to look horribly convoluted, but please help me understand what's happening. from functools import partial class Cage(object): def __init__(self, animal): self.animal = animal def…
noio
  • 5,744
  • 7
  • 44
  • 61
112
votes
3 answers

Swift @escaping and Completion Handler

I am trying to understand 'Closure' of Swift more precisely. But @escaping and Completion Handler are too difficult to understand I searched many Swift postings and official documents, but I felt it was still not enough. This is the code example of…
PrepareFor
  • 2,448
  • 6
  • 22
  • 36
111
votes
6 answers

What does $0 and $1 mean in Swift Closures?

let sortedNumbers = numbers.sort { $0 > $1 } print(sortedNumbers) Can anyone explain what $0 and $1 means in Swift? Another Sample array.forEach { actions.append($0) }
aashish tamsya
  • 4,903
  • 3
  • 23
  • 34
107
votes
2 answers

Accessing outside variable using anonymous function as params

Basically I use this handy function to processing db rows (close an eye on PDO and/or other stuff) function fetch($query,$func) { $query = mysql_query($query); while($r = mysql_fetch_assoc($query)) { $func($r); } } With this…
dynamic
  • 46,985
  • 55
  • 154
  • 231
107
votes
7 answers

Closure in Java 7

What is closure? It is supposed to be included in Java 7. (Closures were discussed for inclusion in Java 7, but in the end were not included. -ed) Can anyone please provide me with some reliable references from where I can learn stuff about…
Swaranga Sarma
  • 13,055
  • 19
  • 60
  • 93
106
votes
7 answers

Blocks on Swift (animateWithDuration:animations:completion:)

I'm having trouble making the blocks work on Swift. Here's an example that worked (without completion block): UIView.animateWithDuration(0.07) { self.someButton.alpha = 1 } or alternatively without the trailing…
manolosavi
  • 1,113
  • 2
  • 7
  • 10
102
votes
2 answers

Why do we need fibers

For Fibers we have got classic example: generating of Fibonacci numbers fib = Fiber.new do x, y = 0, 1 loop do Fiber.yield y x,y = y,x+y end end Why do we need Fibers here? I can rewrite this with just the same Proc (closure,…
fl00r
  • 82,987
  • 33
  • 217
  • 237
101
votes
6 answers

PHP 7.2 Function create_function() is deprecated

I have used create_function() in my application below. $callbacks[$delimiter] = create_function('$matches', "return '$delimiter' . strtolower(\$matches[1]);"); But for PHP 7.2.0, create_function() is deprecated. How do I rewrite my code above for…
Saly
  • 1,446
  • 3
  • 11
  • 18
101
votes
1 answer

Access to Modified Closure (2)

This is an extension of question from Access to Modified Closure. I just want to verify if the following is actually safe enough for production use. List lists = new List(); //Code to retrieve lists from DB foreach (string list…
faulty
  • 8,117
  • 12
  • 44
  • 61
101
votes
13 answers

Can you explain closures (as they relate to Python)?

I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that…
knowncitizen
  • 1,523
  • 2
  • 17
  • 21