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
4
votes
3 answers

How does this JavaScript closure work?

Here's some JavaScript: linkElem.click(function () { var data = linkElem.data(); alert(''+data.mls + ' ' + data.id); }); It works. linkElem is a local variable that I create in a loop inside a function. I assign some data to it with…
Fletcher Moore
  • 13,558
  • 11
  • 40
  • 58
4
votes
2 answers

Ruby Closures: How to return args and block as a single argument to pass to a method

Suppose I have a method that takes args and a block: def yield_if_widget(*args, &block) if args[0].is_a?(Widget) block.call end end I can call this method with arguments and a block: yield_if_widget(Widget.new) do puts "I like…
Isaac Betesh
  • 2,935
  • 28
  • 37
4
votes
2 answers

Functions in Lua could store local values between calls?

I'm reading "Programming in Lua" and I don't understand behavior of function in Lua in this piece of code: function newCounter () local i = 0 return function () -- anonymous function i = i + 1 return i end end c1 =…
corund
  • 157
  • 6
4
votes
2 answers

Groovy's inconsistent destructuring / decomposition on lists?

Positive Case: Can get into a list groovy> println GroovySystem.version groovy> final data1 = [[99,2] , [100,4]] groovy> data1.collect{x,y->x+y} 2.2.1 Result: [101, 104] Negative Case: Can not do the same groovy> println GroovySystem.version …
mert inan
  • 1,537
  • 2
  • 15
  • 26
4
votes
2 answers

What is the difference between these two ways of declaring prototype methods?

I've been writing coffeescript for a little while now and ran into something a bit peculiar. Traditionally coffeescript declares all prototype methods individually like such: MyClass.prototype.firstMethod =…
4
votes
1 answer

Casting closures in Swift?

It seems that closures of compatible parameter and return types can't be cast( up or down ). I want to store arrays of callbacks in a Dictionary, where the key can be used to determine the type of the callback's parameter. Just casting won't…
Gregzo
  • 1,194
  • 7
  • 18
4
votes
5 answers

modified closure warning in ReSharper

I was hoping someone could explain to me what bad thing could happen in this code, which causes ReSharper to give an 'Access to modified closure' warning: bool result = true; foreach (string key in keys.TakeWhile(key => result)) { result =…
Sarah Vessels
  • 30,930
  • 33
  • 155
  • 222
4
votes
1 answer

How to use Groovy's replaceFirst with closure?

I'm a newbie on Groovy and have a question about replaceFirst with closure. The groovy-jdk API doc gives me examples of... assert "hellO world" == "hello world".replaceFirst("(o)") { it[0].toUpperCase() } // first match assert "hellO wOrld" ==…
sgil
  • 45
  • 1
  • 4
4
votes
1 answer

How to create a closure for a C function

I am using the C API to interact with ECL and I am trying to create a closure object from a native function that has some stored state. I have tried this: cl_object f(long nargs, ...) { std::cout << nargs << std::endl; std::cout << "has…
Cpp Man
  • 108
  • 5
4
votes
1 answer

Nested closures and captured variables

I have this example with nested closures which demonstrates memory leak use v5.10; use strict; package Awesome; sub new { bless {steps => [], surprise => undef}, shift; } sub say { print "awesome: ", $_[1], "\n"; } sub prepare { my…
Oleg G
  • 925
  • 4
  • 12
4
votes
3 answers

Passing property type as parameter

Is there a way to pass the property to a function as a parameter ? class Car { let doors : Int = 4 let price : Int = 1000 } Is there a way to pass the Car property as a type to a function ? I would like to achieve the following: func…
user1046037
  • 16,755
  • 12
  • 92
  • 138
4
votes
1 answer

How to debug JavaScript closure state?

I have this code snippet that scientifically accurate calculates the speed of a cat according to the amount of legs it has. function Cat() { var self = this; var _legs = 0; self.addLeg = function() { _legs++; } …
Dirk Boer
  • 8,522
  • 13
  • 63
  • 111
4
votes
3 answers

One all-encompassing definition of JavaScript closure

I have read 10s of SO references on closures, MDN references and other blog articles. They all seem to define closures in their own ways. For example, From MDN documentation: function makeFunc() { var name = "Mozilla"; function displayName() { …
Athapali
  • 1,091
  • 4
  • 25
  • 48
4
votes
2 answers

Getting data out of a closure in swift

I have made a query in parse and fetched an array of GeoPoint coordinates. This was done inside a closure. I can only access the array values inside that closure. I need to be able to use those value so they can be used as annotations on a map but I…
user4184036
4
votes
1 answer

Swift Sort an array with multiple sort criteria

How is an array sorted by multiple criteria in Swift? For example, an array of dictionaries as shown: items = [ [ "item":"itemA" "status":"0" "category":"B" ],[ "item":"itemB" "status":"1" …
Michael Voccola
  • 1,827
  • 6
  • 20
  • 46
1 2 3
99
100