Skip to content

Instantly share code, notes, and snippets.

@jugglinmike
Created August 27, 2011 16:39
Show Gist options
  • Save jugglinmike/1175578 to your computer and use it in GitHub Desktop.
Save jugglinmike/1175578 to your computer and use it in GitHub Desktop.
Memoizing Example for "Avoiding the Quirks"
// Examples based on those given in
// "Avoiding The Quirks: Lessons From A JavaScript Code Review"
// by Addy Osmani
// http://addyosmani.com/blog/lessons-from-a-javascript-code-review/
// Branching at runtime with memoization
// (wordy version)
var utils = {
getXHR: function() {
if( !this.memoized || typeof this.memoized !== 'function' ) {
if(window.XMLHttpRequest) {
this.memoized = function() { return new XMLHttpRequest(); };
} else if(window.ActiveXObject) {
/*this has been simplified for example sakes*/
this.memozied = function() { return new ActiveXObject('Microsoft.XMLHTTP'); };
}
}
return this.memoized();
}
};
// Subtler (and more efficient) version
var utils = {
getXHR: function() {
if(window.XMLHttpRequest) {
utils.getXHR = function() {
return new XMLHttpRequest;
}
} else if(window.ActiveXObject) {
utils.getXHR = function(){
/*this has been simplified for example sakes*/
return new ActiveXObject('Microsoft.XMLHTTP');
}
}
return utils.getXHR();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment