ncyoung.com

closures... why?

This entry is in the following categories:

Top->Programming->Web->JavaScript/DHTML
 - Older in JavaScript/DHTML: bookmarklet heaven
 - Newer in JavaScript/DHTML: google suggests

I just read a really good article on closures in javascript, both how to use them and how to recognize when you have created one accidentally...

I got to thinking though and couldn't come up with a need to use closures where objects wouldn't work as well. Here's my simple proof of concept:

NOTE: I have found that in many cases you can use a closure where you need a function with parameters to be set up as the event handler to a node when you're DOM programming.

<script>
function defineThing (instanceParam){

var instanceInternalCounter=0;

function thing (callParam){
instanceInternalCounter++;
var msg = "I was instantiated with " + instanceParam;
msg = msg + " and called with " + callParam;
msg = msg + ". I have been called " + instanceInternalCounter + " times.
";
document.write(msg);
}

return thing;
}

document.write("with closures:
");

var thing8 = defineThing(8);
thing8(4);
thing8(16);





function makeThing(instanceParam){

this.instP = instanceParam;
this.count = 0;
this.thing = thing;

}

function thing (callParam){
this.count++;
var msg = "I was instantiated with " + this.instP;
msg = msg + " and called with " + callParam;
msg = msg + ". I have been called " + this.count + " times.
";
document.write(msg);
}


document.write("

with object:
");

var thingObj8 = new makeThing(8);
thingObj8.thing(4);
thingObj8.thing(16);






</script>

and here it is in action:





Dated: 07/08/2004