Nitpicking, just one small thing: given Douglas Crockford's and others' advice, do you really want the starting {
on a separate line?
Short example: JavaScript Style - why ita€?s important
try{ transport = new ActiveXObject("MSXML2.XMLHTTP.6.0"); }catch(e){}
try{ transport = new ActiveXObject("MSXML2.XMLHTTP"); }catch(e){}
Shouldn't the order of those lines be reversed? That way IE7 users with the XHR object disabled will get the 6.0 instead of the 3.0. Or am I not following? It seems to me that, in IE7 with XHR disabled, the first statement will succeed and the transport variable will reference the 6.0 version. And then the second statement will also succeed and the transport variable will now reference the 3.0 version.
@Chris A: Good catch. I've updated the code example in the article with an IF check in the second TRY statement. (Now to put together my first errata for the book...)
I usually return the object as soon as possible i.e.
try {
return new ActiveXObject("Msxml2.XMLHTTP.6.0");
} catch(e) {
try {
return new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
return null;
}
}
Yes, that solves that specific issue. But to me, at least, it seems like sound advice to always have it on the same line as the code, to avoid any potential hazards with semi-colons inserted automatically by the interpretor.
Very nice!
Robert,
There are no known issues with having your beginning bracket on a new line and accidental semi-colon insertion when dealing with functions, for/while-loops, if/then statements, etc in JavaScript. Even Crockford does some of his code this way.
The issue comes into focus when you are dealing with objects.
I should correct my last statement above to say:
The issue comes into focus when you are dealing with literals.
Breaking after a parenthesis is perfectly fine.
Being an ECMAScript Engine author, I shall call you on that.
Semicolons are technically *required* after break, continue, return and throw statements, and newline is now allowed between break and any following identifier token. Any engine which assumes a newline after a break is a semicolon is violating standard.
When I code in it, I always explicitly write it;
I might also mention that:
if(window.XMLHttpRequest)
return new XMLHttpRequest();
else if(window.ActiveXObject)
return new ActiveXObject("msxml2.xmlhttp");
else
throw new Error("Could not find XMLHttpRequest Object");
works fine, provided you remember to put open before onreadystatechange.
Regards,
Dan
Hi! Ebanij vrot! tb7oh8ki77 vn254iax6g!
ceea ce I was privire pentru, multumesc
Yes, I still prefer putting the { on a new line. I find it easier for seeing where my functions start and end. For
return
s, I don't like returning an object literal, so I'll always assign it to a variable and then return the variable. I find the code more readable that way and, as it turns out, avoids the issue described.