jQuery
xhr: function() { return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(); }
JavaScript框架设计
// 缓存 function xhr() { if (!xhr.cache) { var fns = [ function () { return new XMLHttpRequest(); }, function () { return new ActiveXObject('Msxml2.XMLHTTP'); }, function () { return new ActiveXObject('Microsoft.XMLHTTP'); }, ]; for (var i = 0, n = fns.length; i < n; i++) { try { fns[i](); xhr.cache = fns[i]; break; } catch(e) {} } return xhr.cache(); } else { return xhr.cache(); } } var xhrObject = xhr(); //调用 alert(xhrObject) //[object XMLHttpRequest]
var xhr = function() { var fns = [ function () { return new XMLHttpRequest(); }, function () { return new ActiveXObject('Msxml2.XMLHTTP'); }, function () { return new ActiveXObject('Microsoft.XMLHTTP'); }, ]; for (var i = 0, n = fns.length; i < n; i++) { try { fns[i](); xhr = fns[i];//注意这里,覆写自身 break; }catch(e) {} } return xhr() } console.log(xhr) console.log(xhr()) console.log(xhr) console.log(xhr())
window.$ = {} var s = ["XMLHttpRequest", "ActiveXObject('Msxml2.XMLHTTP.6.0')","ActiveXObject('Msxml2.XMLHTTP.3.0')", "ActiveXObject('Msxml2.XMLHTTP')"]; if (!"1"[0]) { //判定IE67 s[0] = location.protocol === "file:" ? "!" : s[0]; // 报异常,跳过 } for (var i = 0, axo; axo = s[i++]; ) { try { if (eval("new " + axo)) { $.xhr = new Function("return new " + axo); break; } } catch (e) {} }
我们再认真思考一下,既然我们是写框架,那么这些检测其实是放在 IIFE 里面,因此基本不用覆写,检测好哪个可用,就把它加到命名空间上就好了。最后的版本就出来了,使用new Function、eval,反正只用一次,耗不了多少性能