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
1 answer

Does Func callbacks can cause memory leak?

Everybody know that eventhandlers that are never removed for the invocationList can cause memory leak in C#. My questions is, Can we have memory leak if we use Func as callback? (therefore supporting only one subscriber) Take the following example…
Lineker
  • 305
  • 1
  • 9
4
votes
2 answers

how to throw errors in a closure in swift?

Please look at the following code: override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { let deleteAction = UITableViewRowAction(style:…
user3788747
  • 112
  • 2
  • 11
4
votes
1 answer

For-loop incrementing to limit before being passed to function

I have some code to copy files contained in an array for each source and destination directory in a dirs array. Each iteration through the loop, it calls the function that copies. It looks like this: var filesInEachDir ["file1", "file2",…
1252748
  • 14,597
  • 32
  • 109
  • 229
4
votes
3 answers

Assigning a lambda as a parameter to a generic method called through reflection

Consider a generic method as follow: class SomeClass { public static void SomeMethod(Func); } I would like to call this method using reflection. This is how far I could make it: _SomeMethod = typeof(SomeClass).GetMethod("SomeMethod", …
Mehran
  • 15,593
  • 27
  • 122
  • 221
4
votes
4 answers

Using a Closure as a While Loop's Condition

I want to use a closure as a condition for a while loop. This is what I have: var x: Int = 0 var closure = {() -> Bool in return x > 10} while closure { x += 1 println(x) // never prints } It never prints anything. If I change it to…
4
votes
2 answers

Track completion of javascript callbacks without nesting functions

So I'm writing a function that makes a bunch of database calls. I want to store their results in an array and trigger a callback once they're all done. Some pseudocode may help: function getStuff (array, callback) { var results = []; var…
Cheezey
  • 700
  • 2
  • 11
  • 29
4
votes
1 answer

How to make a variable update work in riot js

Loving riot js but why is "Hello 0" not incrementing on the page in the following code example, and what is the workaround for now?

Hello {myNumber}

this.myNumber = 0; var thisApp = this; setInterval( …
Navigateur
  • 1,852
  • 3
  • 23
  • 39
4
votes
1 answer

PHP closure in other closure : scope of "use"

I have a code that looks like this : $app->add(function($req, $res, $next) { # closure A $res->on('end', function($res) use ($req) { # closure B }); $next(); }); As you can see, I have a closure in a closure. Closure B is…
Morgan Touverey Quilling
  • 4,181
  • 4
  • 29
  • 41
4
votes
1 answer

How can you quickly view a variable type in Xcode and Swift?

For example, if I'm inside a closure and I say, ... { response, data, error in ... } Is there a way for me to view the types of response, data, and error very quickly? Right now, the only way I can do this without doing a println and building my…
rb612
  • 5,280
  • 3
  • 30
  • 68
4
votes
1 answer

Swift initialize a struct with a closure

public struct Style { public var test : Int? public init(_ build:(Style) -> Void) { build(self) } } var s = Style { value in value.test = 1 } gives an error at the declaration of the variable Cannot find an initializer for…
Andy Jacobs
  • 15,187
  • 13
  • 60
  • 91
4
votes
1 answer

Scala: lazy vals, call by name, closures and memory leaks

I have a scala procedure creating a large data structure using an even larger index in the process. Because I want to do it in one pass and not get boggled down in complicated precedence resolution, I'm using lazy vals in the result initialized with…
Turin
  • 2,208
  • 15
  • 23
4
votes
2 answers

Should every function be a closure?

Since closures and the ability to call a function later with its closed over variables seems to be a big plus with javascript's capabilities, I'm finding myself constantly using the following construct: var func; func = function (args) {return…
ciso
  • 2,887
  • 6
  • 33
  • 58
4
votes
1 answer

Reusing closures in Swift

Which of the following is better: Sample1: var x: Int = 0 for _ in 1...5 { someList.append( Foobar(someClosure: { println("X = \(x)") })) } Sample2: var x: Int = 0 var c: ()->() = { println("X = \(x)") } for _ in 1...5 { someList.append(…
user1040049
4
votes
2 answers

How to use @autoclosure parameter in async block in Swift?

I would like to call an @autoclosure parameter inside dispatch_async block. func myFunc(@autoclosure condition: () -> Bool) { dispatch_async(dispatch_get_main_queue()) { if condition() { println("Condition is true") } } } I get…
Evgenii
  • 36,389
  • 27
  • 134
  • 170
4
votes
3 answers

Multiple where clause in YII2

I have a Question, How to use Closure type Active records Query in YII2 with conditional WHERE. Here what i want to achive: public function getUsers($limit = 10, $type = 1, $company_id = 0) { return User::find()->where( function($query) use…
Nadeem Latif
  • 174
  • 1
  • 6
1 2 3
99
100