Created
June 14, 2011 21:48
-
-
Save vanm/1025997 to your computer and use it in GitHub Desktop.
MS Closure Examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // MS example of a memory leak "caused by closure" | |
| hookup(document.getElementById('menu')); | |
| function hookup(element) { | |
| // Reference to #menu element available within | |
| // mouse scope via closure | |
| function mouse (){} | |
| // mouse attached to #menu element via event. | |
| element.attachEvent( "onmouseover", mouse); | |
| } | |
| // -------------------------------------------------------- | |
| // MS proposed solution: Don't use closures | |
| // (safe but not convenient or practical) | |
| hookup(document.getElementById('menu')); | |
| // No access to #menu element within | |
| // mouse scope (except via `this` keyword) | |
| function mouse () {} | |
| function hookup(element) { | |
| element.attachEvent( "onmouseover", mouse); | |
| } | |
| //------------------------------------------------- | |
| // Solution 2: Create another closure | |
| // notice: element argument has been removed | |
| hookup(); | |
| function hookup() { | |
| // Mouse has no access to element in | |
| // it's scope (except through `this`) | |
| function mouse () {} | |
| (function(){ | |
| // Reference creation within closure to contain scope. | |
| var element = document.getElementById('menu'); | |
| element.attachEvent( "onmouseover", mouse); | |
| })(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment