Created
June 17, 2015 16:29
-
-
Save NouranMahmoud/3fee57bd30c34a92e223 to your computer and use it in GitHub Desktop.
Branching is a technique that allows you to encapsulate browser differences into dynamic methods that get set at run-time. Once the initialization is complete, each browser only executes the code specific to its implementation of Javascript.
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
/* SimpleXhrFactory signleton, step2 */ | |
var SimpleXhrFactory = (function(){ | |
//The three branches. | |
var standard = { | |
createXhrObject: function(){ | |
return new XMLHttpRequest(); | |
} | |
}; | |
var activeXNew = { | |
createXhrObject: function(){ | |
return new ActiveXObject('Msxml2.XMLHTTP'); | |
} | |
}; | |
var activeXOld = { | |
createXhrObject: function(){ | |
return new ActiveXObject('Microsoft.XMLHTTP'); | |
} | |
}; | |
//To assign the branch, try each method; return whatever doesn't fail. | |
var testObject; | |
try{ | |
testObject = standard.createXhrObject(); | |
return standard; //Return this if no error was thrown. | |
} | |
catch(e){ | |
try{ | |
testObject = standard.createXhrObject(); | |
return standard; //Return this if no error was thrown | |
} | |
catch(e){ | |
try{ | |
testObject = activeXOld.createXhrObject(); | |
return activeXOld; //Return this if no error was thrown. | |
} | |
catch(e){ | |
thrown new Error('No XHR object found in this environment.'); | |
} | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment