Skip to content

Instantly share code, notes, and snippets.

@vanm
Created June 14, 2011 21:48
Show Gist options
  • Select an option

  • Save vanm/1025997 to your computer and use it in GitHub Desktop.

Select an option

Save vanm/1025997 to your computer and use it in GitHub Desktop.
MS Closure Examples
// 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