9,053 questions
7610
votes
86
answers
1.6m
views
How do JavaScript closures work?
How would you explain JavaScript closures to someone with a knowledge of the concepts they consist of (for example functions, variables and the like), but does not understand closures themselves?
I ...
835
votes
43
answers
895k
views
Static variables in JavaScript
How can I create static variables in Javascript?
986
votes
26
answers
597k
views
How are lambdas useful? [closed]
I'm trying to figure out Python lambdas. Is lambda one of those "interesting" language items that in real life should be forgotten?
I'm sure there are some edge cases where it might be ...
1
vote
1
answer
104
views
How to call an async closure multiple times [duplicate]
I am trying to get the following simple apply function to compile (simlified for example):
struct Context(i32);
pub async fn apply<F, Fut>(ctx: &mut Context, f: F)
where
F: Fn(&mut ...
1
vote
1
answer
86
views
Why doesn’t new Function have access to local variables in JavaScript? [duplicate]
I was experimenting with closures in JavaScript and ran into something confusing.
function outer() {
let x = 10;
return new Function("return x;");
}
const fn = outer();
console.log(fn());
I ...
5
votes
1
answer
75
views
Why does this code that moves a closure into another closure and returns both even compile?
I have the following code:
fn test() -> (impl FnMut(&mut u8), impl FnMut(&mut u8)) {
let a = |v: &mut u8| {*v = 0};
let b = move |v: &mut u8| { a(v); println!("{}&...
0
votes
1
answer
183
views
Why is a lambda expression not just the syntactic sugar of a functor?
Consider the following code:
int main() {
int n = 0;
return [n] { return n; }(); // ok
}
According to https://cppinsights.io, the code above will be translated into the following code:
int ...
580
votes
12
answers
123k
views
JavaScript closures vs. anonymous functions
A friend of mine and I are currently discussing what is a closure in JS and what isn't. We just want to make sure we really understand it correctly.
Let's take this example. We have a counting loop ...
491
votes
6
answers
250k
views
In PHP, what is a closure and why does it use the "use" identifier?
I'm checking out some PHP 5.3.0 features and ran across some code on the site that looks quite funny:
public function getTotal($tax)
{
$total = 0.00;
$callback =
/* This line here: */...
-2
votes
1
answer
71
views
Will new object assignment to same GLOBAL variable cause memory leaks?
I'm trying to set GLOBAL variable available across all modules of Node.js app.
module.exports = app => {
app.get('/config', async (req, res) => {
.....
const { data } = await axios....
384
votes
10
answers
177k
views
What underlies the `var self = this` JavaScript idiom?
I saw the following in the source for WebKit HTML 5 SQL Storage Notes Demo:
function Note() {
var self = this;
var note = document.createElement('div');
note.className = 'note';
note....
2
votes
1
answer
92
views
powershell -Action Scriptblock doesn't care about closure
My problem is fairly simple:
I'm trying to execute a file on a timer elapsed event.
I use a closure to preserve the value of my variable.
But I think I struggle to understand what is the lifetime of ...
385
votes
8
answers
97k
views
What do lambda function closures capture? [duplicate]
Recently I started playing around with Python and I came around something peculiar in the way closures work. Consider the following code:
adders = [None, None, None, None]
for i in [0, 1, 2, 3]:
...
0
votes
1
answer
59
views
Create mutable iterator over a set of indices?
I'm trying to implement an array where items can occupy multiple slots (details not relevant to question).
I have created a method that allows me to iterate over a range of items:
pub fn get(&self,...
0
votes
1
answer
96
views
Why does Rust consider an owning closure to exist for 'static lifetime?
I was considering the possibility of passing a closure that owns some thread-safe value, to a spawned thread. The thread would then be able to call something only knowing the signature, while the ...
1
vote
1
answer
51
views
dptree::filter_async problem with move semantic
I'm writing a bot on Rust via teloxide + tokio. I have this run method (called from main)
pub async fn run() {
dotenv::dotenv().ok();
pretty_env_logger::init();
log::info!("Starting ...
7
votes
1
answer
233
views
Why do I need an apparently useless type annotation when a closure matches against an enum-with-lifetime argument?
Here's a minimal reproduction for an issue I was having in a larger codebase:
enum A<'b> {
A1(&'b u8)
}
fn consume_fnmut(_f: &mut impl FnMut (A)) {}
// Desugared:
// fn ...
1
vote
1
answer
57
views
Lua stack and vararg functions
I'm curently exploring Lua (5.4.7) vm implementation, it's relatively simple but i can't figure our how return works in case of vararg functions.
functions with fixed amount of params are quite simple,...
189
votes
3
answers
134k
views
Closure use of non-escaping parameter may allow it to escape
I have a protocol:
enum DataFetchResult {
case success(data: Data)
case failure
}
protocol DataServiceType {
func fetchData(location: String, completion: (DataFetchResult) -> (Void))
...
294
votes
11
answers
83k
views
Captured variable in a loop in C#
I met an interesting issue about C#. I have code like below.
List<Func<int>> actions = new List<Func<int>>();
int variable = 0;
while (variable < 5)
{
actions.Add(() =&...
237
votes
9
answers
117k
views
Creating functions (or lambdas) in a loop (or comprehension)
I'm trying to create functions inside of a loop:
functions = []
for i in range(3):
def f():
return i
functions.append(f)
Alternatively, with lambda:
functions = []
for i in range(3):...
158
votes
8
answers
136k
views
Store a closure as a variable in Swift
In Objective-C, you can define a block's input and output, store one of those blocks that's passed in to a method, then use that block later:
// in .h
typedef void (^...
113
votes
6
answers
85k
views
What does $0 and $1 mean in Swift Closures?
let sortedNumbers = numbers.sort { $0 > $1 }
print(sortedNumbers)
Can anyone explain what $0 and $1 means in Swift?
Another Sample
array.forEach {
actions.append($0)
}
229
votes
8
answers
333k
views
Why does this UnboundLocalError occur (closure)? [duplicate]
What am I doing wrong here?
counter = 0
def increment():
counter += 1
increment()
The above code throws an UnboundLocalError.
227
votes
12
answers
54k
views
What are 'closures' in .NET?
What is a closure? Do we have them in .NET?
If they do exist in .NET, could you please provide a code snippet (preferably in C#) explaining it?