Return statement in if statement

89 views Asked by At

I am experiencing some strange behavior in IE10. I needed to use ActiveXObject to get some files locally (via the file:// protocol).

Why does this work in IE10:

function createXhr() {
  return new window.ActiveXObject( "Microsoft.XMLHTTP" );
}

But not this:

function createXhr() {
  inMpage = true;

 if (inMpage == false) {
   var a = new window.XMLHttpRequest();
 } else {
   var a = new window.ActiveXObject( "Microsoft.XMLHTTP" );
 }

 return a;
}
1

There are 1 answers

0
SK. On

Because all modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have a built-in XMLHttpRequest object.

var a = new window.XMLHttpRequest(); // use this for IE10

and your code is executing else case which is compatible with old versions of Internet Explorer (IE5 and IE6) not with IE10.

var a = new window.ActiveXObject( "Microsoft.XMLHTTP" );

To handle all modern browsers, including IE5 and IE6, check if the browser supports the XMLHttpRequest object. If it does, create an XMLHttpRequest object, if not, create an ActiveXObject:

var xmlhttp;
if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
} else {
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}