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

Cannot call a function in a spawned thread because it "does not fulfill the required lifetime"

I can run this code fn testf(host: &str) {} fn start(host: &str) { testf(host); testf(host); } but for some reason, I can't run this one: fn testf(host: &str) {} fn start(host: &str) { thread::spawn(move || testf(host)); …
Bogdan Ruzhitskiy
  • 1,167
  • 1
  • 12
  • 21
4
votes
1 answer

Closure actions should be defined on controller

Ember 1.13.10 I wanted to try out the closure actions, so I defined the a route: import Ember from 'ember'; export default Ember.Route.extend({ actions: { doSave() { ... } } }); and the template: {{my-component onSave=(action…
Willem de Wit
  • 8,604
  • 9
  • 57
  • 90
4
votes
1 answer

Does ES2015 exported class create a closure?

As it's currently compiled via Babel + Webpack, module's exported class will create a closure: variables created inside the module will be shared between class instances. bar.js: let foo; export default class Bar { set foo(value) { foo…
Pavlo
  • 43,301
  • 14
  • 77
  • 113
4
votes
1 answer

R programming: cache the inverse of a matrix

I am following a Data Science course on Coursera and I have a question regarding one of the assignments where I have to inverse a Matrix and then cache that result. Basically I have been googling away and I found the answer but there are parts of…
Mick
  • 324
  • 4
  • 14
4
votes
1 answer

Strange behaviour in invoking closures

I wonder why this does not work: (PHP Fatal error: Call to undefined method stdClass::y()) $x=new stdClass; $x->y=function(){return 'hi';}; echo $x->y(); but this works: $x=new stdClass; $x->y=function(){return 'hi';}; $y=$x->y; echo $y(); echo…
Handsome Nerd
  • 17,114
  • 22
  • 95
  • 173
4
votes
1 answer

What's the difference between for and foreach in respect to closure

The demo code has some problems. var values = new List() { 100, 110, 120 }; var funcs = new List>(); foreach(var v in values) funcs.Add( ()=>v ); foreach(var f in funcs) Console.WriteLine(f()); Most people…
huoxudong125
  • 1,966
  • 2
  • 26
  • 42
4
votes
1 answer

Closures get parent function name

Bash is “kind of function programming language” it dose not have classes. I managed to use encapsulation with Closures, but I want also to do some introspection to find also docker_ parent/super/base function (If you know add comments to define this…
Andrei.Danciuc
  • 1,000
  • 10
  • 24
4
votes
2 answers

Passing data into Task Continuation

I have the following method : private void GetHistoricalRawDataFromTextFiles(MessageHeader header, HistoricalRawDataFromTextFileSubscriptionDto dto) { var computeInstance = GetComputeInstance(dto.SubscriberId, dto.ComputeInstanceId); var…
Matt
  • 7,004
  • 11
  • 71
  • 117
4
votes
1 answer

Spark TaskNotSerializable when using anonymous function

Background Here's my situation: I'm trying to create a class that filters an RDD based on some feature of the contents, but that feature can be different in different scenarios so I'd like to parameterize that with a function. Unfortunately, I seem…
Patrick
  • 861
  • 6
  • 12
4
votes
2 answers

RelayCommand from lambda with constructor parameters

If, in a XAML file, I bind a Button to "Command" from the following class, then clicking the Button does not cause DoIt to be executed: class Thing() { public Thing(Foo p1) { Command = new RelayCommand(() => DoIt(p1)); } private…
theguy
  • 861
  • 9
  • 19
4
votes
2 answers

How to return an outer function inside an asynchronous inner function in swift?

I am creating a swift class which contain of a function which validate if the user is true. However, the userVerifyResult will always return "false" even if the result is true due to dataTaskWithRequest function is executed asynchronously. How can I…
dramasea
  • 3,370
  • 16
  • 49
  • 77
4
votes
2 answers

Closures vs Classes?

I have the concept of a "Rule" that I want to be able to process. As such, I created the Interface below: public interface IRule { Boolean IsSatisfiedBy(T value); String GetViolationMessage(T value); } I had planned on creating a…
Chris Baxter
  • 16,083
  • 9
  • 51
  • 72
4
votes
1 answer

How to change external variable's value inside a goroutine closure

func (this *l) PostUpload(ctx *Context) { //ctx.Response.Status = 500 l, err := models.NewL(this.Config) go func() { err = l.Save(file) if err != nil { ctx.Response.Status = 500 …
hkx_1030
  • 153
  • 1
  • 3
  • 7
4
votes
4 answers

Function pointers working as closures in C++

Is there a way in C++ to effectively create a closure which will be a function pointer? I am using the Gnu Scientific Library and I have to create a gsl_function. This function needs to effectively "close" a couple of parameters available when I…
Grzenio
  • 35,875
  • 47
  • 158
  • 240
4
votes
2 answers

How do I access variables that are inside closures in Swift?

I'm new to Swift and I'm trying to get the result from this function. I don't know how to access variables that are inside the closure that is passed to the sendAsynchronousRequest function from outside the closure. I have read the chapter on…
Questioner
  • 2,451
  • 4
  • 29
  • 50