var self = this?

This question is not specific to jQuery, but specific to JavaScript in general. The core problem is how to “channel” a variable in embedded functions. This is the example: var abc = 1; // we want to use this variable in embedded functions function xyz(){ console.log(abc); // it is available here! function qwe(){ console.log(abc); // … Read more

What are ‘closures’ in .NET?

I have an article on this very topic. (It has lots of examples.) In essence, a closure is a block of code which can be executed at a later time, but which maintains the environment in which it was first created – i.e. it can still use the local variables etc of the method which … Read more

Why does this UnboundLocalError occur (closure)? [duplicate]

Python doesn’t have variable declarations, so it has to figure out the scope of variables itself. It does so by a simple rule: If there is an assignment to a variable inside a function, that variable is considered local.[1] Thus, the line counter += 1 implicitly makes counter local to increment(). Trying to execute this … Read more

Javascript infamous Loop issue? [duplicate]

Quoting myself for an explanation of the first example: JavaScript’s scopes are function-level, not block-level, and creating a closure just means that the enclosing scope gets added to the lexical environment of the enclosed function. After the loop terminates, the function-level variable i has the value 5, and that’s what the inner function ‘sees’. In … Read more

Why aren’t python nested functions called closures?

A closure occurs when a function has access to a local variable from an enclosing scope that has finished its execution. def make_printer(msg): def printer(): print(msg) return printer printer = make_printer(‘Foo!’) printer() When make_printer is called, a new frame is put on the stack with the compiled code for the printer function as a constant … Read more

Access to Modified Closure

In this case, it’s okay, since you are actually executing the delegate within the loop. If you were saving the delegate and using it later, however, you’d find that all of the delegates would throw exceptions when trying to access files[i] – they’re capturing the variable i rather than its value at the time of … Read more

What is a practical use for a closure in JavaScript?

Suppose, you want to count the number of times user clicked a button on a webpage. For this, you are triggering a function on onclick event of button to update the count of the variable <button onclick=”updateClickCount()”>click me</button> Now there could be many approaches like: You could use a global variable, and a function to … Read more