Created
August 27, 2011 16:39
-
-
Save jugglinmike/1175578 to your computer and use it in GitHub Desktop.
Memoizing Example for "Avoiding the Quirks"
This file contains 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
// 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