Skip to content

Anonymous functions bind to references #4412

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
JanChec opened this issue Dec 28, 2016 · 2 comments
Closed

Anonymous functions bind to references #4412

JanChec opened this issue Dec 28, 2016 · 2 comments

Comments

@JanChec
Copy link

JanChec commented Dec 28, 2016

Code:

for i in [0..2]
  setTimeout (-> console.log(i)), i * 500
  i2 = JSON.parse(JSON.stringify(i))  # superdirty value copy
  setTimeout (-> console.log(i2)), i2 * 500 + 250

Output:

3
2
3
2
3
2

^ in 250ms intervals - good, also correct order.

Expected:

0
0
1
1
2
2

^ in 250ms intervals.

@JanChec JanChec changed the title Generator output variables are overwritten Anonymous functions bind to references Dec 28, 2016
@JanChec
Copy link
Author

JanChec commented Dec 28, 2016

This is by design, a common solution is binding values by wrapping in another function:

for i in [0..2]
  boundLog = (text) -> (-> console.log(text))
  setTimeout boundLog(i), i * 500
  (...)

Hm, maybe some syntactic sugar for this?

@vendethiel
Copy link
Collaborator

I think you want #2518.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants