Thursday, November 13, 2014

getting closure

Just a reminder about Self Excuting Anonymous Functions.. they're a great way to avoid polluting a page's global name space if you are making a script to be included on someone else's page (like in the window.onload event, where you don't want to leave a remnant.)

Some code I did today had bits like this:

(function (){
var oldOnLoad = window.onload;
window.onload = function(e){
if(typeof oldOnLoad  == "function"){

That was a decent way to not overwrite any existing window.onload code, but oldOnLoad isn't in the global space, because of the use of the closure.

No comments:

Post a Comment