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
100
votes
6 answers

What is this JavaScript pattern called and why is it used?

I'm studying THREE.js and noticed a pattern where functions are defined like so: var foo = ( function () { var bar = new Bar(); return function ( ) { //actual logic using bar from above. //return result; …
Patrick Klug
  • 14,056
  • 13
  • 71
  • 118
97
votes
11 answers

How do you test functions and closures for equality?

The book says that "functions and closures are reference types". So, how do you find out if the references are equal? == and === don't work. func a() { } let å = a let b = å === å // Could not find an overload for === that accepts the supplied…
user652038
94
votes
2 answers

How to call a closure that is a class variable?

class MyClass { var $lambda; function __construct() { $this->lambda = function() {echo 'hello world';}; // no errors here, so I assume that this is legal } } $myInstance = new MyClass(); $myInstance->lambda(); //Fatal error: Call to…
rsk82
  • 28,217
  • 50
  • 150
  • 240
93
votes
2 answers

How do I store a closure in a struct in Rust?

Before Rust 1.0, I could write a structure using this obsolete closure syntax: struct Foo { pub foo: |usize| -> usize, } Now I can do something like: struct Foo usize> { pub foo: F, } But then what's the type of a Foo…
bfops
  • 5,348
  • 5
  • 36
  • 48
93
votes
2 answers

Python lambda's binding to local values

The following code spits out 1 twice, but I expect to see 0 and then 1. def pv(v) : print v x = [] for v in range(2): x.append(lambda : pv(v)) for xx in x: xx() I expected python lambdas to bind to the reference a local variable is pointing…
Hassan Syed
  • 20,075
  • 11
  • 87
  • 171
91
votes
6 answers

JavaScript function aliasing doesn't seem to work

I was just reading this question and wanted to try the alias method rather than the function-wrapper method, but I couldn't seem to get it to work in either Firefox 3 or 3.5beta4, or Google Chrome, both in their debug windows and in a test web…
Kev
  • 15,899
  • 15
  • 79
  • 112
90
votes
8 answers

Closures in PHP... what, precisely, are they and when would you need to use them?

So I'm programming along in a nice, up to date, object oriented fashion. I regularly make use of the various aspects of OOP that PHP implements but I am wondering when might I need to use closures. Any experts out there that can shed some light on…
rg88
  • 20,742
  • 18
  • 76
  • 110
89
votes
12 answers

Function pointers, Closures, and Lambda

I am just now learning about function pointers and, as I was reading the K&R chapter on the subject, the first thing that hit me was, "Hey, this is kinda like a closure." I knew this assumption is fundamentally wrong somehow and after a search…
None
  • 2,927
  • 3
  • 29
  • 42
86
votes
8 answers

Are defaults in JDK 8 a form of multiple inheritance in Java?

A new feature coming in JDK 8 allows you to add to an existing interface while preserving binary compatibility. The syntax is like public interface SomeInterface() { void existingInterface(); void newInterface() default…
Pyrolistical
  • 27,624
  • 21
  • 81
  • 106
84
votes
5 answers

Is it possible to make a recursive closure in Rust?

This is a very simple example, but how would I do something similar to: let fact = |x: u32| { match x { 0 => 1, _ => x * fact(x - 1), } }; I know that this specific example can be easily done with iteration, but I'm…
Undeterminant
  • 1,210
  • 1
  • 8
  • 14
83
votes
5 answers

Mutable variable is accessible from closure. How can I fix this?

I am using Typeahead by twitter. I am running into this warning from Intellij. This is causing the "window.location.href" for each link to be the last item in my list of items. How can I fix my code? Below is my code: AutoSuggest.prototype.config =…
iCodeLikeImDrunk
  • 17,085
  • 35
  • 108
  • 169
82
votes
3 answers

Use keyword in functions - PHP

Possible Duplicate: In Php 5.3.0 what is the Function “Use” Identifier ? Should a sane programmer use it? I've been examining the Closures in PHP and this is what took my attention: public function getTotal($tax) { $total = 0.00; …
Tarik
  • 79,711
  • 83
  • 236
  • 349
81
votes
1 answer

What are 'closures' in C#?

Duplicate Closures in .NET What are closures in C#?
Shane Scott
  • 1,583
  • 2
  • 13
  • 11
81
votes
7 answers

The foreach identifier and closures

In the two following snippets, is the first one safe or must you do the second one? By safe I mean is each thread guaranteed to call the method on the Foo from the same loop iteration in which the thread was created? Or must you copy the reference…
xyz
  • 27,223
  • 29
  • 105
  • 125
78
votes
1 answer

Closure vs Anonymous function (difference?)

Possible Duplicates: What is Closures/Lambda in PHP or Javascript in layman terms? What is the difference between a 'closure' and a 'lambda'? Hi, I have been unable to find a definition that clearly explains the differences between a closure and…
Maxim Gershkovich
  • 45,951
  • 44
  • 147
  • 243