JavaScript设计模式之单体模式全面解析(2)

// 利用单体的分支技术来定义XHR(XMLHttpRequest)对象,必须要用闭包才可以实现 var XHR = (function(){ //The three branches var standard = { cXHR:function(){ return new XMLHttpRequest(); } }; var activeXNew = { cXHR:function(){ return new ActiveXObject('Msxml2.XMLHttp'); } }; var activeXOld = { cXHR:function(){ return new ActiveXObject('Microsoft.XMLHttp'); } }; //To assign(分配) the branch, try each method;return whatever doesn't fail var testObject; try{ testObject = standard.cXHR(); return standard;// return this branch if no error was thrown }catch(e){ try{ testObject = activeXNew.cXHR(); return activeXNew; }catch(e){ try{ testObject = activeXOld.cXHR(); return activeXOld; }catch(e){ throw new Error('Create the XMLHttpRequestObject failed!'); } } } })(); window.onload = function(){ alert(XHR.cXHR()); }

以上所述是小编给大家介绍的JavaScript设计模式之单体模式全面解析,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wzjpzx.html