Timeline for Is this a JavaScript closure bug?
Current License: CC BY-SA 3.0
12 events
| when toggle format | what | by | license | comment | |
|---|---|---|---|---|---|
| Oct 7, 2013 at 3:13 | vote | accept | Fede | ||
| Oct 6, 2013 at 5:58 | audit | Suggested edits | |||
| Oct 6, 2013 at 5:59 | |||||
| Oct 3, 2013 at 21:24 | history | edited | Fede | CC BY-SA 3.0 |
added 919 characters in body
|
| Oct 3, 2013 at 16:16 | comment | added | Beetroot-Beetroot |
To help understand the interpretation of this in functions, try reading John Resig's excellent article Simple "Class" Instantiation. Unless you are a total genius, you won't understand every word first time - I have read it a dozen times and still need to go back to it on occasions. It provides enormous insight.
|
|
| Oct 3, 2013 at 7:03 | comment | added | slebetman |
See my answer to this other question for a full description of how this works in javascript: stackoverflow.com/questions/13441307/…
|
|
| Oct 3, 2013 at 7:00 | comment | added | slebetman |
In your code, this refers to the global object, which in web browsers is window. So what you're doing is creating ONE global called closure which is referenced via this.closure and you keep replacing THE SAME variable with a new function. Hence, when setTimeout executes it logically executes the last function assigned, three times. If you call the function with new instead a new empty object will be created (inheriting from the function's prototype) and assigned to this. Either way, this has nothing to do with closures but rather the concept of this in javascript.
|
|
| Oct 3, 2013 at 6:04 | history | edited | Fede | CC BY-SA 3.0 |
added 325 characters in body
|
| Oct 3, 2013 at 5:57 | answer | added | 6502 | timeline score: 3 | |
| Oct 3, 2013 at 5:53 | review | First posts | |||
| Oct 3, 2013 at 5:54 | |||||
| Oct 3, 2013 at 5:46 | history | edited | Fede | CC BY-SA 3.0 |
edited body
|
| Oct 3, 2013 at 5:39 | answer | added | Denys Séguret | timeline score: 1 | |
| Oct 3, 2013 at 5:36 | history | asked | Fede | CC BY-SA 3.0 |