简体   繁体   English

jQuery为什么在try / catch中包装XHR对象的创建?

[英]Why does jQuery wrap XHR object creation in try / catch?

If I had to write my own cross-browser AJAX function without jQuery (which I do), I would do this: 如果我必须编写没有jQuery的跨浏览器AJAX函数(我这样做),则可以这样做:

var getXHR = function() {
  if (window.XMLHttpRequest) {
    return new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    return new ActiveXObject('Microsoft.XMLHTTP');
  }
}

But while digging through jQuery's source code , I noticed this: 但是在浏览jQuery的源代码时 ,我注意到了这一点:

function createStandardXHR() {
  try {
    return new window.XMLHttpRequest();
  } catch( e ) {}
}
function createActiveXHR() {
  try {
    return new window.ActiveXObject( "Microsoft.XMLHTTP" );
  }
}

Then: 然后:

createStandardXHR() || createActiveXHR();

Why do the jQuery developers just call the object constructors directly inside of a try/catch block, rather than using feature detection. 为什么jQuery开发人员只在try/catch块内直接调用对象构造函数,而不是使用特征检测。 I imagine a try/catch is slower than a simple if check. 我想try/catch比简单的if检查要慢。 What is the benefit? 有什么好处?

Your method is good. 你的方法很好。
After reading the code, I think the developers of jQuery uses this trick to create the Request object and test !this.isLocal && /^(get|post|head|put|delete|options)$/i.test( this.type ) && in a single statement without error. 阅读代码后,我认为jQuery的开发人员使用此技巧创建了Request对象并测试!this.isLocal && /^(get|post|head|put|delete|options)$/i.test( this.type ) &&在单个语句中没有错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM