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
2 answers

Calling a Stack-Allocated Closure Stored in a Struct in Rust

I am storing a closure in a struct like this: #[derive(Clone)] struct S<'a> { func: &'a FnOnce() -> u32 } fn main() { let s = S { func: &|| 0 }; let val = (s.func)(); println!("{}", val); } When I compile, s.func cannot be moved to…
cderwin
  • 425
  • 4
  • 11
4
votes
2 answers

Why do we need a weakSelf for functions/methods within closures?

Reading my own answer. I fully understand why we need a weakSelf for members/properties. They could create memory cycles. But properties have a memory location. Do functions also have memory locations?! I mean isn't a function something just…
mfaani
  • 33,269
  • 19
  • 164
  • 293
4
votes
4 answers

How does the JS scope of these blocks work?

Can anyone explain why the following produces 1,2 and the other produces 5? Should they not both produce 5? //produces 1,2 (function () { var a = [5]; function bar() { if (!a) { var a = [1, 2]; } …
Harvester316
  • 381
  • 1
  • 8
  • 17
4
votes
2 answers

How do I return a boxed closure from a method that has a reference to the struct?

I have a structure that contains a value and I want to obtain a function that operates on this value: struct Returner { val: i32, } impl<'a> Returner { fn get(&'a self) -> Box i32> { Box::new(|x| x + self.val) …
Month
  • 293
  • 1
  • 11
4
votes
1 answer

Julia - Defining a function that outputs a function

I'm trying to create a small function to define the Hamiltonian flow if inputted the functions the Hamiltonian consists of. E.g. I would like to define function makeThedH(f::Function,g::Function) dH1(s,u) = cos(u[3]).*f(u[1],u[2]); dH2(s,u) =…
Aaron Chen
  • 43
  • 4
4
votes
1 answer

Is there a let / flet / labels like concept for binding closures to avoid funcall?

Whilst going over let over lambda I happened across (defmacro! dlambda (&rest ds) `(lambda (&rest ,g!args) (case (car ,g!args) ,@(mapcar (lambda (d) `(,(if (eq t (car d)) t …
cheshirecatalyst
  • 379
  • 1
  • 5
  • 14
4
votes
1 answer

NSLock.lock() executed while lock already held?

I'm reviewing some Alamofire sample Retrier code: func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) { lock.lock() ; defer { lock.unlock() } if let…
Marcus Leon
  • 55,199
  • 118
  • 297
  • 429
4
votes
1 answer

Capturing values in nested closures

What is proper syntax for using captured value in nested closure? I have following working code for calculating CRC32 from integer value using zlib library. func testCrc() { var x: UInt32 = 0xffffffff let result = withUnsafePointer(to: &x,…
Dalija Prasnikar
  • 27,212
  • 44
  • 82
  • 159
4
votes
1 answer

D3: Using a closure to update a selection without re-binding data

I have lifted the following code from Mike Bostock's example of using D3 to create a line drawing tool. This tool creates a drag behaviour that enables the user to draw a curve by dragging on the SVG canvas. When the drag behaviour starts, the…
act
  • 143
  • 1
  • 5
4
votes
2 answers

Refer back to old iterator value in click() function for javascript/jQuery (closure question)

I'm trying to get the "click()" function to display the value of 'i' at the time I passed in the function. But its referring back to the value of 'i' after it finished. I'm drawing a blank on how to get the function to refer to the value of 'i'…
Chris Dutrow
  • 48,402
  • 65
  • 188
  • 258
4
votes
3 answers

Scoping Issues inside jQuery.ajax()

I'm caching label strings by saving them into a variable, but running into weird scoping issues. I know this has to do with closures, but I can't seem to figure out what the issue is exactly. info_lbl =…
alkos333
  • 631
  • 6
  • 11
4
votes
1 answer

Why do changes to an Object passed to a closure persist in global scope?

var x = 1; (function(x, j) { j.fn.cool = function() {}; x = 2; })(x, jQuery); console.log(jQuery.fn.cool); // returns the newly added function I noticed this happens not with just jQuery, so I assume it's related to…
adi518
  • 863
  • 1
  • 11
  • 19
4
votes
1 answer

Swift: Difference between closure, completion handler and function?

Can anyone let me know what are advantages of closures over functions? When should we use closures and functions with example ?
Srikanth Adavalli
  • 665
  • 1
  • 10
  • 25
4
votes
0 answers

What are "cell variables" in Python?

I've heard the term "cell variable" for many places(e.g. when people talking about the super() magic of Python and closure), but I can't find its definition on this site or in the documentation. So, I think this question is necessary: What's a "cell…
nalzok
  • 14,965
  • 21
  • 72
  • 139
4
votes
1 answer

Passing a closure that modifies its environment to a function in Rust

I have a closure that captures and modifies its environment. I want to pass this closure to a function that accepts closures: fn main() { let mut integer = 5; let mut closure_variable = || -> i32 { integer += 1; integer …
Johan
  • 342
  • 3
  • 14